Compare commits

..

101 Commits

Author SHA1 Message Date
Vincent Koc
af3c10626c test(plugin): align prerelease rpc lane contract 2026-06-19 06:49:46 +02:00
Vincent Koc
324ad548a8 fix(release): keep ClawHub verification bodies timed 2026-06-19 06:36:55 +02:00
Vincent Koc
e552f97866 refactor(irc): drop unused text splitter 2026-06-19 12:36:41 +08:00
Vincent Koc
259f071a93 fix(signal): report receive websocket pre-open closes 2026-06-19 06:34:46 +02:00
liuhao1024
a5190f7d4a fix(skills/trello): add curl to requires.bins to match body examples (fixes #94727) (#94729)
Summary:
- The PR adds `curl` to the bundled Trello skill's `metadata.openclaw.requires.bins` entry.
- PR surface: Docs 0. Total 0 across 1 file.
- Reproducibility: yes. at source level. Current main and v2026.6.8 declare only `jq` for Trello while the skill body uses `curl`, and the shared requirement evaluator checks only declared bins.

Automerge notes:
- No ClawSweeper repair was needed after automerge opt-in.

Validation:
- ClawSweeper review passed for head 83ae5e8bef.
- Required merge gates passed before the squash merge.

Prepared head SHA: 83ae5e8bef
Review: https://github.com/openclaw/openclaw/pull/94729#issuecomment-4747397470

Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
2026-06-19 04:33:38 +00:00
Vincent Koc
a619518ebe fix(e2e): keep cross-os response reads timed 2026-06-19 06:31:32 +02:00
Vincent Koc
ea0b0ad0a0 refactor(line): drop unused media kind detector 2026-06-19 12:30:06 +08:00
nas
fb25f29638 fix(codex): bound turn/start text when context budget is non-positive (#94756)
Summary:
- The PR updates Codex context projection fitting so non-positive context budgets still return turn/start text within the app-server input cap while preserving the current user request tail.
- PR surface: Source +23, Tests +87. Total +110 across 2 files.
- Reproducibility: yes. Current main is source-reproducible: when `beforeContext.length + afterContext.length  ... ll-over-limit text; the linked diagnostic also shows the real Codex app-server rejects that pre-fix string.

Automerge notes:
- No ClawSweeper repair was needed after automerge opt-in.

Validation:
- ClawSweeper review passed for head 1510a3d13a.
- Required merge gates passed before the squash merge.

Prepared head SHA: 1510a3d13a
Review: https://github.com/openclaw/openclaw/pull/94756#issuecomment-4747889774

Co-authored-by: Anas <anaselghoudane@gmail.com>
2026-06-19 04:28:27 +00:00
nas
300f5e8590 fix(sessions): preserve Media* index alignment when reading user-turn fields (#94257)
Summary:
- Merged fix(sessions): preserve Media* index alignment when reading user-turn fields after ClawSweeper review.

Automerge notes:
- PR branch already contained follow-up commit before automerge: Merge branch 'main' into fix/media-types-index-alignment

Validation:
- ClawSweeper review passed for head 62db437d10.
- Required merge gates passed before the squash merge.

Prepared head SHA: 62db437d10
Review: https://github.com/openclaw/openclaw/pull/94257#issuecomment-4748486369

Co-authored-by: Anas <anaselghoudane@gmail.com>
Co-authored-by: nas <156536069+Nas01010101@users.noreply.github.com>
Approved-by: vincentkoc
2026-06-19 04:28:14 +00:00
Vincent Koc
f144899219 test(diffs): format viewer client coverage 2026-06-19 06:25:04 +02:00
Vincent Koc
d095e2a4f5 refactor(mattermost): drop unused draft preview helpers 2026-06-19 12:24:35 +08:00
liuhao1024
8aaa4bf3ef test(diffs): add viewerState, toolbar toggle, shadow root, and hydrateProps tests (fixes #83915) (#92873)
Summary:
- Merged test(diffs): add viewerState, toolbar toggle, shadow root, and hydrateProps tests (fixes #83915) after ClawSweeper review.

Automerge notes:
- PR branch already contained follow-up commit before automerge: test(diffs): use real FileContents shape in hydrateProps fixtures

Validation:
- ClawSweeper review passed for head a09ee50584.
- Required merge gates passed before the squash merge.

Prepared head SHA: a09ee50584
Review: https://github.com/openclaw/openclaw/pull/92873#issuecomment-4748453452

Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
Approved-by: vincentkoc
2026-06-19 04:19:54 +00:00
Vincent Koc
06b6f7055b fix(e2e): keep clickclack fixture body reads timed 2026-06-19 06:19:21 +02:00
Vincent Koc
de95726177 fix(googlechat): format approval capability import 2026-06-19 06:18:38 +02:00
Vincent Koc
e91c17947b test(cron): cover force run mode 2026-06-19 06:18:38 +02:00
Vincent Koc
a25c64a4e4 refactor(diffs): drop unused language hint filter 2026-06-19 12:17:46 +08:00
Stellar鱼
8888bca752 test(browser): cover action-input CLI request bodies (#92574)
Summary:
- The branch adds Vitest coverage for browser action-input CLI request bodies across element, navigation/resize, fill/evaluate, and upload paths, plus blank-ref validation.
- PR surface: Tests +278. Total +278 across 4 files.
- Reproducibility: yes. for a source-level coverage gap: current main exposes the browser action-input command ... isting tests still lack broad success-path request-body assertions. This is not a runtime bug reproduction.

Automerge notes:
- PR branch already contained follow-up commit before automerge: test(browser): cover click-coords action body

Validation:
- ClawSweeper review passed for head c070a8d51b.
- Required merge gates passed before the squash merge.

Prepared head SHA: c070a8d51b
Review: https://github.com/openclaw/openclaw/pull/92574#issuecomment-4697124920

Co-authored-by: Stellar鱼 <2182712990@qq.com>
Co-authored-by: yu-xin-c <2182712990@qq.com>
2026-06-19 04:17:29 +00:00
Hidetsugu55
50a4bb00e5 fix(gateway): never return an empty chat.history transcript (#92383)
Summary:
- The PR changes gateway chat-history byte-budget fallback behavior to return a small metadata-free unavailable sentinel instead of an empty transcript, with focused budget tests.
- PR surface: Source +20, Tests +73. Total +93 across 2 files.
- Reproducibility: yes. Source inspection shows current main reaches `messages: []` when the full history, las ... d copied oversized placeholder all exceed `maxBytes`; I did not run tests because this review is read-only.

Automerge notes:
- PR branch already contained follow-up commit before automerge: test: access __openclaw via bracket notation for no-underscore-dangle

Validation:
- ClawSweeper review passed for head f2fa246ab7.
- Required merge gates passed before the squash merge.

Prepared head SHA: f2fa246ab7
Review: https://github.com/openclaw/openclaw/pull/92383#issuecomment-4688688923

Co-authored-by: Hidetsugu55 <183473679+Hidetsugu55@users.noreply.github.com>
2026-06-19 04:17:02 +00:00
Vincent Koc
de17d5b9ef fix(scripts): fail RPC RTT on websocket pre-open close 2026-06-19 06:16:22 +02:00
Voscko
6a0c3eaf78 fix(android): group settings by intent (#94539)
Summary:
- The PR reorganizes the Android Settings home rows into titled intent sections and adds ShellScreen logic tests for section title mapping and section ordering.
- PR surface: Other +106. Total +106 across 2 files.
- Reproducibility: not applicable. this is a UI organization cleanup rather than a bug report. The relevant ve ... ion path is the before/after Android emulator screenshot proof plus source comparison against current main.

Automerge notes:
- No ClawSweeper repair was needed after automerge opt-in.

Validation:
- ClawSweeper review passed for head da9bf5c5b5.
- Required merge gates passed before the squash merge.

Prepared head SHA: da9bf5c5b5
Review: https://github.com/openclaw/openclaw/pull/94539#issuecomment-4741795253

Co-authored-by: Tosko4 <tosko4@gmail.com>
2026-06-19 04:15:19 +00:00
mushuiyu_xydt
78f948f768 fix(tui): show 0 not ? for fresh-session context tokens in footer (#94337)
Summary:
- The PR extends TUI session info to carry `totalTokensFresh`, maps fresh missing totals to `0`, and adds a focused regression test for the footer merge path.
- PR surface: Source +15, Tests +38. Total +53 across 4 files.
- Reproducibility: yes. at source level: `chat.history` returns session info with `totalTokensFresh`, but curr ...  `null` before footer formatting. I did not run local tests or a live TUI session in this read-only review.

Automerge notes:
- PR branch already contained follow-up commit before automerge: Merge branch 'main' into fix/followup-93798

Validation:
- ClawSweeper review passed for head 43657b52c8.
- Required merge gates passed before the squash merge.

Prepared head SHA: 43657b52c8
Review: https://github.com/openclaw/openclaw/pull/94337#issuecomment-4737123127

Co-authored-by: 杨浩宇0668001029 <yang.haoyu@xydigit.com>
Co-authored-by: mushuiyu_xydt <yang.haoyu@xydigit.com>
2026-06-19 04:10:08 +00:00
Vincent Koc
975340fbd5 fix(audit): cancel stalled advisory body reads 2026-06-19 06:09:34 +02:00
Vincent Koc
7570831ee1 refactor(extensions): drop unused compatibility aliases 2026-06-19 12:08:51 +08:00
Vincent Koc
f2a83a7a71 fix(transcription): preserve websocket session errors 2026-06-19 06:05:24 +02:00
Vincent Koc
d9c66b9c6d fix(e2e): bound upgrade survivor probe body reads 2026-06-19 06:02:31 +02:00
Steven
39328ed692 fix(skills): retarget stale plugin skill symlinks (#86719)
Summary:
- The PR retargets stale generated plugin-skill symlinks when their old target disappeared and adds regression coverage for that case.
- PR surface: Source +11, Tests +17. Total +28 across 2 files.
- Reproducibility: no. high-confidence current-main failure was run in this read-only review. The linked issue ... ased-build filesystem state and source inspection confirms the runtime publisher path that this PR changes.

Automerge notes:
- PR branch already contained follow-up commit before automerge: Merge remote-tracking branch 'upstream/main' into fix/plugin-skill-st…
- PR branch already contained follow-up commit before automerge: fix(skills): unlink generated plugin skill symlinks

Validation:
- ClawSweeper review passed for head 94a9765735.
- Required merge gates passed before the squash merge.

Prepared head SHA: 94a9765735
Review: https://github.com/openclaw/openclaw/pull/86719#issuecomment-4539047343

Co-authored-by: Steven Palmer <palmer.e.steven@gmail.com>
2026-06-19 04:02:05 +00:00
Josh Lehman
8662b9de54 refactor: route sdk session compatibility through accessor (#89904) 2026-06-18 21:00:05 -07:00
Dirk
6504237900 fix(note): prevent clack from re-breaking copy-sensitive tokens (#94746)
Summary:
- The PR widens the virtual Clack output columns for wrapped terminal notes and adds a rendered-output regression test for copy-sensitive session-lock paths.
- PR surface: Source +8, Tests +28. Total +36 across 2 files.
- Reproducibility: yes. Current source routes session lock paths through `note()`, and the pinned Clack note renderer hard-wraps final content from `getColumns(output) - 6` after OpenClaw's first wrapping pass.

Automerge notes:
- PR branch already contained follow-up commit before automerge: test(note): add rendered-output regression test for copy-sensitive to…

Validation:
- ClawSweeper review passed for head b17a4ff571.
- Required merge gates passed before the squash merge.

Prepared head SHA: b17a4ff571
Review: https://github.com/openclaw/openclaw/pull/94746#issuecomment-4747714518

Co-authored-by: Dirk <0668000837@xydigit.com>
2026-06-19 03:59:09 +00:00
Vincent Koc
fb69db6365 refactor(extensions): drop unused approval and tunnel helpers 2026-06-19 11:59:05 +08:00
Vincent Koc
845ad1cf71 fix(tooling): timeout transitive manifest packuments 2026-06-19 05:55:00 +02:00
jincheng-xydt
356a199bd4 fix: default cron runMode to "due" instead of "force" (#94270) (#94453)
* fix: default cron runMode to 'due' instead of 'force'

When the runMode parameter is omitted from a cron 'run' action,
the default value now respects schedule guards ('due') instead
of bypassing them ('force'). This prevents unintended execution
of scheduled jobs outside their configured time windows.

Fixes #94270

Co-Authored-By: Claude <noreply@anthropic.com>

* test: update runMode expectations for default 'due' (#94270)

* ci: trigger re-evaluation of real behavior proof

* fix(cron): document due-by-default agent runs

Signed-off-by: sallyom <somalley@redhat.com>

---------

Signed-off-by: sallyom <somalley@redhat.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: sallyom <somalley@redhat.com>
2026-06-18 23:53:17 -04:00
Josh Lehman
f1cab04966 refactor: route SDK session compatibility through seam (#89203) 2026-06-18 20:52:46 -07:00
Yuval Dinodia
87854e841e fix(whatsapp): keep opening text chunk when first media fails on multi-chunk reply (#93823)
Summary:
- The PR changes the WhatsApp auto-reply first-media failure fallback to resend the saved leading caption chunk and adds a multi-chunk regression test for that failure path.
- PR surface: Source 0, Tests +26. Total +26 across 2 files.
- Reproducibility: yes. Source inspection of current main gives a deterministic path: the first chunk is shift ... fallback shifts `remainingText` again before checking `caption`; this read-only review did not rerun tests.

Automerge notes:
- No ClawSweeper repair was needed after automerge opt-in.

Validation:
- ClawSweeper review passed for head b609e44654.
- Required merge gates passed before the squash merge.

Prepared head SHA: b609e44654
Review: https://github.com/openclaw/openclaw/pull/93823#issuecomment-4724923171

Co-authored-by: yetval <yetvald@gmail.com>
2026-06-19 03:52:43 +00:00
lizeyu-xydt
508e3bf413 fix: #80507 show dry-run output for message send/poll (#94684)
Summary:
- The branch changes `formatMessageCliText` to render dry-run message output from `result.dryRun` instead of only `handledBy === "dry-run"`.
- PR surface: Source 0. Total 0 across 1 file.
- Reproducibility: yes. source-reproducible. The linked issue has captured CLI output, and current main shows  ... e the formatter still checks `handledBy === "dry-run"`; I did not execute the CLI in this read-only review.

Automerge notes:
- No ClawSweeper repair was needed after automerge opt-in.

Validation:
- ClawSweeper review passed for head dce6d6a0d3.
- Required merge gates passed before the squash merge.

Prepared head SHA: dce6d6a0d3
Review: https://github.com/openclaw/openclaw/pull/94684#issuecomment-4746101038

Co-authored-by: lizeyu-xydt <li.zeyu@xydigit.com>
2026-06-19 03:51:50 +00:00
Vincent Koc
825188cb6a refactor(xai): drop unused sync tool auth helper 2026-06-19 11:48:55 +08:00
Vincent Koc
36bfe77db1 fix(github): bound guard response bodies 2026-06-19 05:47:19 +02:00
Vincent Koc
def4c995ac fix(ui): isolate gateway callback errors 2026-06-19 05:43:45 +02:00
Vincent Koc
f91350485c refactor(voice-call): drop unused voice lookup helpers 2026-06-19 11:43:26 +08:00
Vincent Koc
d91766e5e1 fix(release): bound ClawHub trusted publisher reads 2026-06-19 05:38:59 +02:00
sutra
dae06a203f fix: add self-knowledge docs rule to system prompt (#90882)
Summary:
- This PR replaces the generated Documentation prompt wording with self-knowledge docs-authority guidance and updates prompt tests plus the system-prompt docs.
- PR surface: Source 0, Tests +27, Docs +6. Total +33 across 4 files.
- Reproducibility: yes. from source for the prompt gap: current main and v2026.6.8 have only broad docs-first  ... ledge failure example. I did not run a fresh current-main live model conversation in this read-only review.

Automerge notes:
- PR branch already contained follow-up commit before automerge: fix: strengthen self-knowledge docs prompt
- PR branch already contained follow-up commit before automerge: test: narrow cli prompt tool assertion
- PR branch already contained follow-up commit before automerge: fix: condense self-knowledge docs prompt
- PR branch already contained follow-up commit before automerge: fix: clarify self-knowledge docs authority
- PR branch already contained follow-up commit before automerge: Merge branch 'main' into sutrah/self-knowledge-docs-prompt

Validation:
- ClawSweeper review passed for head 88a7db5d2a.
- Required merge gates passed before the squash merge.

Prepared head SHA: 88a7db5d2a
Review: https://github.com/openclaw/openclaw/pull/90882#issuecomment-4637990339

Co-authored-by: Sutra Hsing <sutrahsing@163.com>
Co-authored-by: sutra <sutrahsing@163.com>
2026-06-19 03:38:36 +00:00
Vincent Koc
52948a1726 refactor(file-transfer): drop unused fs error classifier 2026-06-19 11:34:41 +08:00
Vincent Koc
88c92922e1 fix(release): bound npm registry verification bodies 2026-06-19 05:33:16 +02:00
Vincent Koc
ae6e1fa4d2 fix(sdk): settle connect after observer errors 2026-06-19 05:27:57 +02:00
Vincent Koc
f1c0d5f06f refactor(sessions): drop unused thread parent helper 2026-06-19 11:27:23 +08:00
Vincent Koc
b28fda9ef8 fix(tooling): bound RPC RTT readiness bodies 2026-06-19 05:20:17 +02:00
Vincent Koc
09427aa760 fix(gateway): contain lifecycle callback errors 2026-06-19 05:15:20 +02:00
Vincent Koc
107904c2c5 refactor(pairing): drop unused direct lookup helpers 2026-06-19 11:14:22 +08:00
Vincent Koc
6c82a9fb18 fix(release): bound GitHub API body reads 2026-06-19 05:13:48 +02:00
kevinlin-openai
741f7080a7 feat(codex): support app-server secret refs (#94324)
Co-authored-by: kevinlin-openai <kevin@dendron.so>
2026-06-18 20:10:11 -07:00
Vincent Koc
a1b7118d0f refactor(infra): drop unused apns store wrappers 2026-06-19 11:06:30 +08:00
Vincent Koc
ca6d52e0e8 fix(e2e): bound bundled readyz diagnostics 2026-06-19 05:00:38 +02:00
Vincent Koc
4c55e04e49 refactor(infra): drop unused web push id helpers 2026-06-19 10:59:13 +08:00
Vincent Koc
8d596aa651 fix(sdk): reject work after client close 2026-06-19 04:54:50 +02:00
Vincent Koc
1385da8d3f refactor(infra): drop unused clawhub endpoint clients 2026-06-19 10:53:19 +08:00
Vincent Koc
ad715dfdc9 fix(e2e): abort kitchen sink retry waits 2026-06-19 04:49:43 +02:00
Vincent Koc
d1ab308f5c refactor(infra): trim dead archive facade exports 2026-06-19 10:44:19 +08:00
Vincent Koc
aaceaf8e7c fix(e2e): clear streaming host command timers 2026-06-19 04:37:43 +02:00
Vincent Koc
1492f9906a fix(qa-lab): keep workspace skills in sandbox 2026-06-19 04:33:18 +02:00
Vincent Koc
9ceb970a06 fix(e2e): clear npm update spawn timers 2026-06-19 04:31:34 +02:00
Vincent Koc
c33007ef58 fix(release): scope MiniMax live model gate 2026-06-19 10:26:02 +08:00
Vincent Koc
09a159c913 refactor(config): remove dead quota maintenance facade 2026-06-19 10:25:50 +08:00
Vincent Koc
eedb6678f1 fix(e2e): extend kitchen rpc watchdog 2026-06-19 04:21:10 +02:00
Vincent Koc
459bcd6198 fix(e2e): clean npm update guest scripts 2026-06-19 04:20:42 +02:00
Vincent Koc
1bbc3b6cb6 refactor(config): remove dead async session target resolver 2026-06-19 10:19:41 +08:00
Vincent Koc
6325a8b5f4 fix(e2e): clean Parallels guest temp scripts 2026-06-19 04:13:03 +02:00
Vincent Koc
5805af9dc4 fix(e2e): defer codex live profile exports 2026-06-19 04:09:10 +02:00
Vincent Koc
42bcb3ecb0 refactor(config): remove dead session schema exports 2026-06-19 10:08:24 +08:00
Thomas Krohnfuß
b48238aa88 feat(commands): add /name to rename the current session from chat (#88581)
* Add /name chat command to rename the current session

Adds a `/name <title>` slash command so users can name or rename the
current session directly from any chat channel, instead of only through
the web/admin session manager. This keeps parallel sessions easy to tell
apart from within the chat flow.

Behaviour:
- `/name <title>` sets the session label, reusing the canonical
  `parseSessionLabel` validation (trim, non-empty, max 512 chars) and the
  same cross-store uniqueness rule enforced by the web `sessions.patch`
  path, so chat naming behaves identically to the session manager.
- `/name` with no argument shows the current name plus a locally derived
  `deriveSessionTitle` suggestion without mutating anything (no LLM).
- Only authorized senders can rename (rejectUnauthorizedCommand), matching
  /goal. The label surfaces everywhere sessions.list is shown (TUI, web,
  CLI, MCP).

The handler resolves the session via resolveSessionStoreEntry so renames
land on the canonical entry even when the store still holds a legacy or
case-folded key alias, and excludes those aliases from the uniqueness scan
to avoid false conflicts. Failed renames skip the store write.

Registers the command in commands-registry.shared.ts and the handler in
loadCommandHandlers, documents it in docs/tools/slash-commands.md, and adds
unit tests covering rename, no-arg suggestion, duplicate-label rejection,
unauthorized senders, disabled text commands, and persisted-name re-read.

Part of the chat-native session naming feature (follows the web in-chat
rename PR). Relates to openclaw#85502 and openclaw#54397.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix(name): seed native sessions and persist renames via canonical key

Address Codex review on PR #88581:
- Fall back to the in-memory params.sessionEntry when the store has no row
  yet, so a brand-new native slash session can be named from its first
  /name command instead of failing with 'no active session to name'.
- Persist the rename through resolved.normalizedKey and drop legacy/
  case-folded alias keys (mirroring persistResolvedSessionEntry) so the
  canonical entry is updated and sessions.list stops surfacing the stale
  alias row.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix(name): emit session metadata changes

Route successful /name renames through the shared command session metadata seam so subscribed session lists receive sessions.changed like /goal.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* feat(commands): add /name to rename the current session from chat

* fix(docs): document the /name slash command

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Agent <agent@example.com>
Co-authored-by: openclaw-clownfish[bot] <280122609+openclaw-clownfish[bot]@users.noreply.github.com>
2026-06-19 10:04:28 +08:00
Vincent Koc
dc980273e3 fix(e2e): align live timeout wrappers 2026-06-19 04:01:43 +02:00
Vincent Koc
74f90885f3 fix(release): unblock beta validation 2026-06-19 10:01:28 +08:00
Vincent Koc
236a0c8fe0 test(auto-reply): inline dead group mention fixture 2026-06-19 10:01:17 +08:00
Vincent Koc
b306745f64 fix(e2e): forward plugin lifecycle poll interval 2026-06-19 03:56:03 +02:00
Stellar鱼
20dd2be0f2 fix(agents): skip auth gate for CLI-owned transport (#88551)
* fix(agents): skip fallback auth gate for CLI runtimes

* fix(agents): skip auth gate for CLI-owned transport

* fix(agents): skip auth gate for CLI-owned transport

---------

Co-authored-by: openclaw-clownfish[bot] <280122609+openclaw-clownfish[bot]@users.noreply.github.com>
2026-06-19 09:54:15 +08:00
Vincent Koc
5b030418c1 refactor(sessions): drop dead transcript tree wrappers 2026-06-19 09:47:31 +08:00
Vincent Koc
a74ce6f20c fix(e2e): forward plugin sweep runtime knobs 2026-06-19 03:46:19 +02:00
Vincent Koc
10f0588ee3 fix(e2e): align codex live turn timeouts 2026-06-19 03:43:44 +02:00
Vincent Koc
39297fb0ad refactor(config): drop dead baseline and node wrappers 2026-06-19 09:41:52 +08:00
Vincent Koc
3914a3638c fix(e2e): forward kitchen sink fixture wait knob 2026-06-19 03:39:04 +02:00
Vincent Koc
2ef0589b76 fix(e2e): forward onboard gateway wait knobs 2026-06-19 03:30:17 +02:00
Vincent Koc
01e562113b fix(e2e): forward doctor switch timeouts 2026-06-19 03:21:28 +02:00
Vincent Koc
410a95269a fix(e2e): pass posix update agent timeouts 2026-06-19 03:19:41 +02:00
Vincent Koc
2c6bf1a5d8 fix(e2e): forward codex media log limit 2026-06-19 03:12:33 +02:00
Vincent Koc
ccc1ad4c74 refactor(auto-reply): remove stale tool meta helpers 2026-06-19 09:11:42 +08:00
Vincent Koc
f19cae6d1d test(ci): cover chat tools helper routing 2026-06-19 09:10:35 +08:00
Vincent Koc
8c3185d55c fix(e2e): forward bundled upgrade limits 2026-06-19 03:06:36 +02:00
Vincent Koc
a0d9f9ea45 fix(e2e): forward bundled plugin runtime limits 2026-06-19 03:02:01 +02:00
Vincent Koc
dd5febe2aa fix(config): preserve raw snapshots after materialization 2026-06-19 09:01:54 +08:00
Vincent Koc
943511674c fix(config): preserve raw snapshots after materialization 2026-06-19 09:01:03 +08:00
Vincent Koc
c33cec04d9 refactor(agents): remove stale file transcript rewrite 2026-06-19 08:57:00 +08:00
Vincent Koc
c9605779ef fix(doctor): warn on volatile SQLite state (#94725)
* fix(doctor): warn on volatile SQLite state

* fix(doctor): resolve symlinked state paths
2026-06-19 08:56:37 +08:00
Vincent Koc
c79f1e5441 fix(e2e): forward package assertion limits 2026-06-19 02:49:47 +02:00
Vincent Koc
15e101137d fix(e2e): forward live plugin scan limit 2026-06-19 02:48:30 +02:00
Vincent Koc
900a834c60 refactor(daemon): remove stale launchd helpers 2026-06-19 08:45:50 +08:00
Vincent Koc
9765f7333a fix(e2e): forward live plugin dump limit 2026-06-19 02:42:10 +02:00
Vincent Koc
1fb11ab306 fix(e2e): forward browser cdp snapshot limit 2026-06-19 02:40:09 +02:00
Vincent Koc
01b919aeff refactor(doctor): remove stale legacy path listers 2026-06-19 08:39:31 +08:00
Vincent Koc
c654641e0c refactor(channels): remove stale setup adapter lookup 2026-06-19 08:33:04 +08:00
Vincent Koc
d04cedb9fe fix(e2e): forward gateway network client limits 2026-06-19 02:30:53 +02:00
Vincent Koc
ba69d4fb03 test(ci): cover installer timeout normalization 2026-06-19 08:29:07 +08:00
Hani Koshaji
73241d39f6 fix(skills/1password): stop forcing tmux for desktop app auth (#52540) (#81825)
* fix(skills/1password): stop forcing tmux for desktop app auth (#52540)

The bundled skill currently mandates that every `op` invocation run inside
a fresh tmux session. That guidance is wrong on every desktop-app-integration
setup (macOS/Windows/Linux) because the 1Password app exposes the CLI over
a per-user Unix domain socket the gateway exec env can reach but tmux
subshells generally cannot — wrapping in tmux produces "1Password CLI
couldn't connect to the 1Password desktop app" failures.

Rewrite the skill to detect auth mode first and only use tmux for the one
case where it actually helps:

- Service account (`OP_SERVICE_ACCOUNT_TOKEN`): direct exec, no signin.
- Desktop app integration: direct exec, never tmux. Note the macOS socket
  location (`~/Library/Group Containers/2BUA8C4S2C.com.1password/t/`) so
  agents can recognize the failure mode.
- Standalone interactive signin: tmux is the right tool because it
  preserves the per-shell session token written by `op signin`.

Update Guardrails and the get-started reference accordingly. Drop the
blanket 'do not run op outside tmux' rule.

Fixes #52540

* fix(skills/1password): correct desktop-app IPC wording and signin example

Address PR #75090 review:

- Replace the blanket 'per-user Unix domain socket' description with
  per-platform wording: XPC via the 1Password Browser Helper on macOS,
  a Unix domain socket on Linux, a named pipe on Windows. Keep the macOS
  group-container path as a symptom indicator only, not as a transport
  claim. Mirror the same correction in the get-started reference and the
  changelog entry.
- Fix the standalone-signin tmux example: `op signin` was being sent as
  a plain command, so its eval-style export was printed but never applied.
  Subsequent `op whoami` and `op vault list` calls would fail because
  the OP_SESSION_* env var was never set. Wrap the call in
  `eval "$(op signin ...)"` so the session token is exported into the
  tmux pane environment as the surrounding text describes.

Same direct-exec direction; tighter and more accurate.

* docs(1password): clarify Windows standalone signin

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* fix(skills/1password): repair auth-mode guidance

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: openclaw-clownfish[bot] <280122609+openclaw-clownfish[bot]@users.noreply.github.com>
2026-06-19 08:26:56 +08:00
Vincent Koc
c770c7b084 refactor(channels): remove stale setup reload helpers 2026-06-19 08:25:38 +08:00
242 changed files with 6497 additions and 2909 deletions

View File

@@ -1686,7 +1686,8 @@ jobs:
FIREWORKS_API_KEY: ${{ secrets.FIREWORKS_API_KEY }}
OPENCLAW_LIVE_PROVIDERS: ${{ matrix.providers }}
OPENCLAW_LIVE_IMAGE: ${{ needs.prepare_live_test_image.outputs.live_image }}
OPENCLAW_LIVE_MAX_MODELS: "6"
OPENCLAW_LIVE_MODELS: ${{ matrix.models || 'modern' }}
OPENCLAW_LIVE_MAX_MODELS: ${{ matrix.max_models || '6' }}
OPENCLAW_LIVE_MODEL_TIMEOUT_MS: "45000"
OPENCLAW_SKIP_DOCKER_BUILD: "1"
OPENCLAW_VITEST_MAX_WORKERS: "2"
@@ -2000,7 +2001,7 @@ jobs:
profiles: stable full
- suite_id: native-live-src-gateway-profiles-minimax
label: Native live gateway profiles MiniMax
command: OPENCLAW_LIVE_GATEWAY_PROVIDERS=minimax,minimax-portal OPENCLAW_LIVE_GATEWAY_MODELS=minimax/MiniMax-M3,minimax-portal/MiniMax-M3 OPENCLAW_LIVE_GATEWAY_MAX_MODELS=2 node .release-harness/scripts/test-live-shard.mjs native-live-src-gateway-profiles
command: OPENCLAW_LIVE_GATEWAY_PROVIDERS=minimax,minimax-portal OPENCLAW_LIVE_GATEWAY_MODELS=minimax/MiniMax-M2.7,minimax-portal/MiniMax-M2.7 OPENCLAW_LIVE_GATEWAY_MAX_MODELS=2 node .release-harness/scripts/test-live-shard.mjs native-live-src-gateway-profiles
timeout_minutes: 60
profile_env_only: false
profiles: stable full
@@ -2303,7 +2304,7 @@ jobs:
profiles: stable full
- suite_id: live-gateway-minimax-docker
label: Docker live gateway MiniMax
command: OPENCLAW_LIVE_GATEWAY_PROVIDERS=minimax,minimax-portal OPENCLAW_LIVE_GATEWAY_MODELS=minimax/MiniMax-M3,minimax-portal/MiniMax-M3 OPENCLAW_LIVE_GATEWAY_MAX_MODELS=1 OPENCLAW_LIVE_GATEWAY_STEP_TIMEOUT_MS=90000 OPENCLAW_LIVE_GATEWAY_MODEL_TIMEOUT_MS=180000 OPENCLAW_LIVE_DOCKER_REPO_ROOT="$GITHUB_WORKSPACE" timeout --foreground --kill-after=30s 35m bash .release-harness/scripts/test-live-gateway-models-docker.sh
command: OPENCLAW_LIVE_GATEWAY_PROVIDERS=minimax,minimax-portal OPENCLAW_LIVE_GATEWAY_MODELS=minimax/MiniMax-M2.7,minimax-portal/MiniMax-M2.7 OPENCLAW_LIVE_GATEWAY_MAX_MODELS=2 OPENCLAW_LIVE_GATEWAY_STEP_TIMEOUT_MS=90000 OPENCLAW_LIVE_GATEWAY_MODEL_TIMEOUT_MS=180000 OPENCLAW_LIVE_DOCKER_REPO_ROOT="$GITHUB_WORKSPACE" timeout --foreground --kill-after=30s 35m bash .release-harness/scripts/test-live-gateway-models-docker.sh
timeout_minutes: 40
profile_env_only: false
profiles: stable full

View File

@@ -45,7 +45,7 @@ on:
kova_ref:
description: openclaw/Kova Git ref to install
required: false
default: b63b6f9e20efb23641df00487e982230d81a90ac
default: 4f146016583018bad9e24f8e64a6af5f963bb7ee
type: string
dispatch_id:
description: Optional parent workflow dispatch identifier
@@ -98,7 +98,7 @@ jobs:
live: "true"
include_filters: "scenario:agent-cold-warm-message"
env:
KOVA_REF: ${{ inputs.kova_ref || 'b63b6f9e20efb23641df00487e982230d81a90ac' }}
KOVA_REF: ${{ inputs.kova_ref || '4f146016583018bad9e24f8e64a6af5f963bb7ee' }}
KOVA_HOME: ${{ github.workspace }}/.artifacts/kova/home/${{ matrix.lane }}
PERFORMANCE_HELPER_DIR: ${{ github.workspace }}/.artifacts/performance-workflow
REPORT_DIR: ${{ github.workspace }}/.artifacts/kova/reports/${{ matrix.lane }}

View File

@@ -898,32 +898,38 @@ private fun SettingsShellScreen(
ProfilePanel(displayName = displayName.ifBlank { "OpenClaw" }, onClick = { onRouteChange(SettingsRoute.Profile) })
}
item {
SettingsGroup(
rows =
listOf(
SettingsRow("Profile", displayName.ifBlank { "Local device" }, Icons.Default.Person, route = SettingsRoute.Profile),
SettingsRow("Voice", if (speakerEnabled) "Speaker on" else "Speaker muted", Icons.Default.Mic, route = SettingsRoute.Voice),
SettingsRow("Agents", if (agents.isEmpty()) "Load from gateway" else "${agents.size} available", Icons.Default.Person, status = agents.isNotEmpty(), route = SettingsRoute.Agents),
SettingsRow("Approvals", approvalsSummary(pendingToolCalls.size), Icons.Default.Lock, status = approvalsStatus(pendingToolCalls.size), route = SettingsRoute.Approvals),
SettingsRow("Cron Jobs", cronJobsSummary(cronStatus.jobs), Icons.Outlined.AccessTime, status = if (cronStatus.jobs > 0) cronStatus.enabled else null, route = SettingsRoute.CronJobs),
SettingsRow("Usage", usageSummaryText(usageSummary.providers.size), Icons.Default.Storage, status = if (usageSummary.providers.isNotEmpty()) true else null, route = SettingsRoute.Usage),
SettingsRow("Skills", skillsSummaryText(skillsSummary.skills), Icons.Default.Settings, status = skillsStatus(skillsSummary.skills), route = SettingsRoute.Skills),
SettingsRow("Nodes & Devices", nodesDevicesSummaryText(nodesDevicesSummary), Icons.Default.Cloud, status = nodesDevicesStatus(nodesDevicesSummary), route = SettingsRoute.NodesDevices),
SettingsRow("Channels", channelsSummaryText(channelsSummary), Icons.Default.Notifications, status = channelsStatus(channelsSummary), route = SettingsRoute.Channels),
SettingsRow("Dreaming", dreamingSummaryText(dreamingSummary), Icons.Default.Storage, status = dreamingStatus(dreamingSummary), route = SettingsRoute.Dreaming),
SettingsRow("Canvas", "Screen surface", Icons.AutoMirrored.Filled.ScreenShare, status = isConnected, route = SettingsRoute.Canvas),
SettingsRow("Notifications", if (notificationForwardingEnabled) "Smart delivery" else "Off", Icons.Default.Notifications, route = SettingsRoute.Notifications),
SettingsRow("Phone Capabilities", if (cameraEnabled) "Camera enabled" else "Locked", Icons.Default.Lock, status = !cameraEnabled, route = SettingsRoute.PhoneCapabilities),
SettingsRow("Gateway", gatewaySummary(statusText, isConnected), Icons.Default.Cloud, status = isConnected, route = SettingsRoute.Gateway),
SettingsRow("Appearance", appearanceThemeSummary(appearanceThemeMode), Icons.Default.Palette, route = SettingsRoute.Appearance),
SettingsRow("Health", "Diagnostics", Icons.Default.Settings, status = isConnected, route = SettingsRoute.Health),
SettingsRow("About", "Version and update", Icons.Default.Storage, route = SettingsRoute.About),
),
onOpen = onRouteChange,
val settingsRows =
listOf(
SettingsRow("Gateway", gatewaySummary(statusText, isConnected), Icons.Default.Cloud, status = isConnected, route = SettingsRoute.Gateway),
SettingsRow("Nodes & Devices", nodesDevicesSummaryText(nodesDevicesSummary), Icons.Default.Cloud, status = nodesDevicesStatus(nodesDevicesSummary), route = SettingsRoute.NodesDevices),
SettingsRow("Channels", channelsSummaryText(channelsSummary), Icons.Default.Notifications, status = channelsStatus(channelsSummary), route = SettingsRoute.Channels),
SettingsRow("Agents", if (agents.isEmpty()) "Load from gateway" else "${agents.size} available", Icons.Default.Person, status = agents.isNotEmpty(), route = SettingsRoute.Agents),
SettingsRow("Approvals", approvalsSummary(pendingToolCalls.size), Icons.Default.Lock, status = approvalsStatus(pendingToolCalls.size), route = SettingsRoute.Approvals),
SettingsRow("Cron Jobs", cronJobsSummary(cronStatus.jobs), Icons.Outlined.AccessTime, status = if (cronStatus.jobs > 0) cronStatus.enabled else null, route = SettingsRoute.CronJobs),
SettingsRow("Usage", usageSummaryText(usageSummary.providers.size), Icons.Default.Storage, status = if (usageSummary.providers.isNotEmpty()) true else null, route = SettingsRoute.Usage),
SettingsRow("Skills", skillsSummaryText(skillsSummary.skills), Icons.Default.Settings, status = skillsStatus(skillsSummary.skills), route = SettingsRoute.Skills),
SettingsRow("Dreaming", dreamingSummaryText(dreamingSummary), Icons.Default.Storage, status = dreamingStatus(dreamingSummary), route = SettingsRoute.Dreaming),
SettingsRow("Voice", if (speakerEnabled) "Speaker on" else "Speaker muted", Icons.Default.Mic, route = SettingsRoute.Voice),
SettingsRow("Canvas", "Screen surface", Icons.AutoMirrored.Filled.ScreenShare, status = isConnected, route = SettingsRoute.Canvas),
SettingsRow("Notifications", if (notificationForwardingEnabled) "Smart delivery" else "Off", Icons.Default.Notifications, route = SettingsRoute.Notifications),
SettingsRow("Phone Capabilities", if (cameraEnabled) "Camera enabled" else "Locked", Icons.Default.Lock, status = !cameraEnabled, route = SettingsRoute.PhoneCapabilities),
SettingsRow("Appearance", appearanceThemeSummary(appearanceThemeMode), Icons.Default.Palette, route = SettingsRoute.Appearance),
SettingsRow("About", "Version and update", Icons.Default.Storage, route = SettingsRoute.About),
SettingsRow("Health", "Diagnostics", Icons.Default.Settings, status = isConnected, route = SettingsRoute.Health),
)
settingsSections(settingsRows).forEach { section ->
item {
SettingsSectionTitle(section.title)
}
item {
SettingsGroup(rows = section.rows, onOpen = onRouteChange)
}
}
item {
SettingsSectionTitle("Account")
}
item {
SettingsGroup(
rows = listOf(SettingsRow("Sign Out", "Disconnect", Icons.AutoMirrored.Filled.ExitToApp)),
@@ -1057,7 +1063,7 @@ private fun dreamingStatus(summary: GatewayDreamingSummary): Boolean? =
else -> null
}
private data class SettingsRow(
internal data class SettingsRow(
val title: String,
val value: String,
val icon: ImageVector,
@@ -1065,6 +1071,65 @@ private data class SettingsRow(
val route: SettingsRoute? = null,
)
internal data class SettingsSection(
val title: String,
val rows: List<SettingsRow>,
)
internal fun settingsSections(rows: List<SettingsRow>): List<SettingsSection> =
settingsSectionOrder.mapNotNull { title ->
val sectionRows = rows.filter { row -> row.route?.let(::settingsSectionTitleForRoute) == title }
if (sectionRows.isEmpty()) null else SettingsSection(title = title, rows = sectionRows)
}
private val settingsSectionOrder =
listOf(
"Connection",
"Agents & automation",
"Phone context & privacy",
"Profile & device",
"Diagnostics",
)
internal fun settingsSectionTitleForRoute(route: SettingsRoute): String =
when (route) {
SettingsRoute.Gateway,
SettingsRoute.NodesDevices,
SettingsRoute.Channels,
-> "Connection"
SettingsRoute.Agents,
SettingsRoute.Approvals,
SettingsRoute.CronJobs,
SettingsRoute.Usage,
SettingsRoute.Skills,
SettingsRoute.Dreaming,
-> "Agents & automation"
SettingsRoute.Voice,
SettingsRoute.Canvas,
SettingsRoute.Notifications,
SettingsRoute.PhoneCapabilities,
-> "Phone context & privacy"
SettingsRoute.Profile,
SettingsRoute.Appearance,
SettingsRoute.About,
-> "Profile & device"
SettingsRoute.Health -> "Diagnostics"
SettingsRoute.Home -> "Diagnostics"
}
@Composable
private fun SettingsSectionTitle(title: String) {
Text(
text = title.uppercase(),
style = ClawTheme.type.caption.copy(fontSize = 12.sp, lineHeight = 16.sp),
color = ClawTheme.colors.textMuted,
)
}
@Composable
private fun ProfilePanel(
displayName: String,

View File

@@ -7,6 +7,8 @@ import ai.openclaw.app.GatewayNodeApprovalState
import ai.openclaw.app.GatewayNodeSummary
import ai.openclaw.app.GatewayNodesDevicesSummary
import ai.openclaw.app.GatewayPendingDeviceSummary
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@@ -155,7 +157,46 @@ class ShellScreenLogicTest {
assertEquals("Node approval pending", rows.single().subtitle)
}
@Test
fun settingsSectionTitlesGroupPowerSettingsByMeaning() {
assertEquals("Connection", settingsSectionTitleForRoute(SettingsRoute.Gateway))
assertEquals("Connection", settingsSectionTitleForRoute(SettingsRoute.NodesDevices))
assertEquals("Agents & automation", settingsSectionTitleForRoute(SettingsRoute.Approvals))
assertEquals("Agents & automation", settingsSectionTitleForRoute(SettingsRoute.CronJobs))
assertEquals("Phone context & privacy", settingsSectionTitleForRoute(SettingsRoute.PhoneCapabilities))
assertEquals("Phone context & privacy", settingsSectionTitleForRoute(SettingsRoute.Notifications))
assertEquals("Profile & device", settingsSectionTitleForRoute(SettingsRoute.Appearance))
assertEquals("Diagnostics", settingsSectionTitleForRoute(SettingsRoute.Health))
}
@Test
fun settingsSectionsPreserveMeaningfulOrder() {
val sections =
settingsSections(
listOf(
settingsRow(SettingsRoute.Voice),
settingsRow(SettingsRoute.Agents),
settingsRow(SettingsRoute.Gateway),
settingsRow(SettingsRoute.Appearance),
settingsRow(SettingsRoute.Health),
),
)
assertEquals(
listOf(
"Connection",
"Agents & automation",
"Phone context & privacy",
"Profile & device",
"Diagnostics",
),
sections.map { it.title },
)
}
private fun emptyChannels(): GatewayChannelsSummary = GatewayChannelsSummary(channels = emptyList())
private fun emptyNodesDevices(): GatewayNodesDevicesSummary = GatewayNodesDevicesSummary(nodes = emptyList(), pendingDevices = emptyList(), pairedDevices = emptyList())
private fun settingsRow(route: SettingsRoute): SettingsRow = SettingsRow(route.name, "Value", Icons.Default.Settings, route = route)
}

View File

@@ -1,2 +1,2 @@
f24065e760a9fafbd2a50962beba4d752b2d6166043170d37cdd6137640e7eef plugin-sdk-api-baseline.json
89a332c206f639d5faef730bac2d23f75751b306419e5dfeae1b731166bbc41c plugin-sdk-api-baseline.jsonl
d991fae868626a78a65ea66389f3d62a48479fe6af3bb2db71a22802aa41ceea plugin-sdk-api-baseline.json
4aa4f623cfc221bca16c00995cd278b15d1706aac074d8016d14e97e1d9423f7 plugin-sdk-api-baseline.jsonl

View File

@@ -315,9 +315,15 @@ The same section also includes the OpenClaw source location. Git checkouts expos
source root so the agent can inspect code directly. Package installs include the GitHub
source URL and tell the agent to review source there whenever the docs are incomplete or
stale. The prompt also notes the public docs mirror, community Discord, and ClawHub
([https://clawhub.ai](https://clawhub.ai)) for skills discovery. It tells the model to
consult docs first for OpenClaw behavior, commands, configuration, or architecture, and to
run `openclaw status` itself when possible (asking the user only when it lacks access).
([https://clawhub.ai](https://clawhub.ai)) for skills discovery. It frames docs as the
authority for OpenClaw self-knowledge before the model understands how OpenClaw works,
including memory/daily notes, sessions, tools, Gateway, config, commands, or project
context. The prompt tells the model to use local docs (or the docs mirror when local docs
are unavailable) first, and to treat AGENTS.md, project context, workspace/profile/memory
notes, and `memory_search` as instruction context or user memory rather than OpenClaw
design or implementation knowledge. If docs are silent or stale, the model should say so
and inspect source. The prompt also tells the model to run `openclaw status` itself when
possible, asking the user only when it lacks access.
For configuration specifically, it points agents to the `gateway` tool action
`config.schema.lookup` for exact field-level docs and constraints, then to
`docs/gateway/configuration.md` and `docs/gateway/configuration-reference.md`

View File

@@ -397,6 +397,7 @@ That stages grounded durable candidates into the short-term dreaming store while
- **State dir permissions**: verifies writability; offers to repair permissions (and emits a `chown` hint when owner/group mismatch is detected).
- **macOS cloud-synced state dir**: warns when state resolves under iCloud Drive (`~/Library/Mobile Documents/com~apple~CloudDocs/...`) or `~/Library/CloudStorage/...` because sync-backed paths can cause slower I/O and lock/sync races.
- **Linux SD or eMMC state dir**: warns when state resolves to an `mmcblk*` mount source, because SD or eMMC-backed random I/O can be slower and wear faster under session and credential writes.
- **Linux volatile state dir**: warns when state resolves to `tmpfs` or `ramfs`, because sessions, credentials, config, and SQLite state with its WAL/journal sidecars will disappear on reboot. Docker `overlay` mounts are intentionally not flagged because their writable layers persist across host reboots while the container remains.
- **Session dirs missing**: `sessions/` and the session store directory are required to persist history and avoid `ENOENT` crashes.
- **Transcript mismatch**: warns when recent session entries have missing transcript files.
- **Main session "1-line JSONL"**: flags when the main transcript has only one line (history is not accumulating).

View File

@@ -91,8 +91,8 @@ Supported `appServer` fields:
| `command` | managed Codex binary | Executable for stdio transport. Leave unset to use the managed binary. |
| `args` | `["app-server", "--listen", "stdio://"]` | Arguments for stdio transport. |
| `url` | unset | WebSocket app-server URL. |
| `authToken` | unset | Bearer token for WebSocket transport. |
| `headers` | `{}` | Extra WebSocket headers. |
| `authToken` | unset | Bearer token for WebSocket transport. Accepts a literal string or SecretInput such as `${CODEX_APP_SERVER_TOKEN}`. |
| `headers` | `{}` | Extra WebSocket headers. Header values accept literal strings or SecretInput values, for example `x-codex-client-session-token: "${CODEX_CLIENT_SESSION_TOKEN}"`. |
| `clearEnv` | `[]` | Extra environment variable names removed from the spawned stdio app-server process after OpenClaw builds its inherited environment. |
| `remoteWorkspaceRoot` | unset | Remote Codex app-server workspace root. When set, OpenClaw infers the local workspace root from the resolved OpenClaw workspace, preserves the current cwd suffix under this remote root, and sends only the final app-server cwd to Codex. If the cwd is outside the resolved OpenClaw workspace root, OpenClaw fails closed instead of sending a gateway-local path to the remote app-server. |
| `requestTimeoutMs` | `60000` | Timeout for app-server control-plane calls. |
@@ -149,11 +149,15 @@ must report stable version `0.125.0` or newer.
OpenClaw treats non-loopback WebSocket app-server URLs as remote and requires
identity-bearing WebSocket auth through `appServer.authToken` or an
`Authorization` header. When native Codex plugins are configured, OpenClaw uses
the connected app-server's plugin control plane to install or refresh those
plugins and then refreshes app inventory so plugin-owned apps are visible to the
Codex thread. Only connect OpenClaw to remote app-servers that are trusted to
accept OpenClaw-managed plugin installs and app inventory refreshes.
`Authorization` header. `appServer.authToken` and each `appServer.headers.*`
value can be a SecretInput; the secrets runtime resolves SecretRefs and env
shorthand before OpenClaw builds app-server start options, and unresolved
structured SecretRefs fail before any token or header is sent. When native Codex
plugins are configured, OpenClaw uses the connected app-server's plugin control
plane to install or refresh those plugins and then refreshes app inventory so
plugin-owned apps are visible to the Codex thread. Only connect OpenClaw to
remote app-servers that are trusted to accept OpenClaw-managed plugin installs
and app inventory refreshes.
## Approval and sandbox modes

View File

@@ -552,8 +552,8 @@ Supported `appServer` fields:
| `command` | managed Codex binary | Executable for stdio transport. Leave unset to use the managed binary; set it only for an explicit override. |
| `args` | `["app-server", "--listen", "stdio://"]` | Arguments for stdio transport. |
| `url` | unset | WebSocket app-server URL. |
| `authToken` | unset | Bearer token for WebSocket transport. |
| `headers` | `{}` | Extra WebSocket headers. |
| `authToken` | unset | Bearer token for WebSocket transport. Accepts a literal string or SecretInput such as `${CODEX_APP_SERVER_TOKEN}`. |
| `headers` | `{}` | Extra WebSocket headers. Header values accept literal strings or SecretInput values, for example `x-codex-client-session-token: "${CODEX_CLIENT_SESSION_TOKEN}"`. |
| `clearEnv` | `[]` | Extra environment variable names removed from the spawned stdio app-server process after OpenClaw builds its inherited environment. OpenClaw keeps per-agent `CODEX_HOME` and inherited `HOME` for local launches. |
| `codeModeOnly` | `false` | Opt into Codex's code-mode-only tool surface. OpenClaw dynamic tools remain registered with Codex so nested `tools.*` calls return through the app-server `item/tool/call` bridge. |
| `remoteWorkspaceRoot` | unset | Remote Codex app-server workspace root. When set, OpenClaw infers the local workspace root from the resolved OpenClaw workspace, preserves the current cwd suffix under this remote root, and sends only the final app-server cwd to Codex. If the cwd is outside the resolved OpenClaw workspace root, OpenClaw fails closed instead of sending a gateway-local path to the remote app-server. |

View File

@@ -164,7 +164,9 @@ two-party event loops that do not go through the shared inbound reply runner.
});
```
Prefer `getSessionEntry(...)`, `listSessionEntries(...)`, `patchSessionEntry(...)`, or `upsertSessionEntry(...)` for session workflows. These helpers address sessions by agent/session identity so plugins do not depend on the legacy `sessions.json` storage shape. Use `preserveActivity: true` for metadata-only patches that should not refresh session activity, and `replaceEntry: true` only when the callback returns a complete entry and deleted fields must stay deleted. `loadSessionStore(...)` remains as a deprecated compatibility escape hatch for callers that intentionally need a mutable whole-store clone.
Prefer `getSessionEntry(...)`, `listSessionEntries(...)`, `patchSessionEntry(...)`, or `upsertSessionEntry(...)` for session workflows. These helpers address sessions by agent/session identity so plugins do not depend on the legacy `sessions.json` storage shape. Use `preserveActivity: true` for metadata-only patches that should not refresh session activity, and `replaceEntry: true` only when the callback returns a complete entry and deleted fields must stay deleted.
`loadSessionStore(...)`, `saveSessionStore(...)`, `updateSessionStore(...)`, and `resolveSessionFilePath(...)` are kept only during the transition before SQLite migration for plugins that still intentionally depend on the legacy whole-store or transcript-file shape. New plugin code must not use those helpers, and existing callers must migrate to entry helpers before the SQLite storage flip.
</Accordion>
<Accordion title="api.runtime.agent.defaults">

View File

@@ -247,7 +247,7 @@ usage endpoint failed or returned no usable usage data.
| `plugin-sdk/reply-history` | Shared short-window reply-history helpers. New message-turn code should use `createChannelHistoryWindow`; lower-level map helpers remain deprecated compatibility exports only |
| `plugin-sdk/reply-reference` | `createReplyReferencePlanner` |
| `plugin-sdk/reply-chunking` | Narrow text/markdown chunking helpers |
| `plugin-sdk/session-store-runtime` | Session workflow helpers (`getSessionEntry`, `listSessionEntries`, `patchSessionEntry`, `upsertSessionEntry`), legacy session store path/session-key helpers, updated-at reads, and deprecated whole-store mutation helpers |
| `plugin-sdk/session-store-runtime` | Session workflow helpers (`getSessionEntry`, `listSessionEntries`, `patchSessionEntry`, `upsertSessionEntry`), legacy session store path/session-key helpers, updated-at reads, and transition-only whole-store/file-path compatibility helpers |
| `plugin-sdk/sqlite-runtime` | Focused SQLite agent-schema, path, and transaction helpers for first-party runtime |
| `plugin-sdk/cron-store-runtime` | Cron store path/load/save helpers |
| `plugin-sdk/state-paths` | State/OAuth dir path helpers |

View File

@@ -43,6 +43,8 @@ Scope intent:
- `tools.web.fetch.firecrawl.apiKey`
- `plugins.entries.acpx.config.mcpServers.*.env.*`
- `plugins.entries.brave.config.webSearch.apiKey`
- `plugins.entries.codex.config.appServer.authToken`
- `plugins.entries.codex.config.appServer.headers.*`
- `plugins.entries.exa.config.webSearch.apiKey`
- `plugins.entries.google-meet.config.realtime.providers.*.apiKey`
- `plugins.entries.google.config.webSearch.apiKey`

View File

@@ -554,6 +554,20 @@
"secretShape": "secret_input",
"optIn": true
},
{
"id": "plugins.entries.codex.config.appServer.authToken",
"configFile": "openclaw.json",
"path": "plugins.entries.codex.config.appServer.authToken",
"secretShape": "secret_input",
"optIn": true
},
{
"id": "plugins.entries.codex.config.appServer.headers.*",
"configFile": "openclaw.json",
"path": "plugins.entries.codex.config.appServer.headers.*",
"secretShape": "secret_input",
"optIn": true
},
{
"id": "plugins.entries.exa.config.webSearch.apiKey",
"configFile": "openclaw.json",

View File

@@ -173,6 +173,7 @@ plugins.
| --- | --- |
| `/new [model]` | Archive the current session and start a fresh one |
| `/reset [soft [message]]` | Reset the current session in place. `soft` keeps the transcript, drops reused CLI backend session ids, and reruns startup |
| `/name <title>` | Name or rename the current session. Omit the title to see the current name and a suggestion |
| `/compact [instructions]` | Compact the session context. See [Compaction](/concepts/compaction) |
| `/stop` | Abort the current run |
| `/session idle <duration\|off>` | Manage thread-binding idle expiry |

View File

@@ -1,11 +1,11 @@
// Bonjour tests cover ciao plugin behavior.
import { describe, expect, it } from "vitest";
const { classifyCiaoUnhandledRejection, ignoreCiaoUnhandledRejection } = await import("./ciao.js");
const { classifyCiaoProcessError } = await import("./ciao.js");
describe("bonjour-ciao", () => {
it("classifies ciao cancellation rejections separately from side effects", () => {
expect(classifyCiaoUnhandledRejection(new Error("CIAO PROBING CANCELLED"))).toEqual({
expect(classifyCiaoProcessError(new Error("CIAO PROBING CANCELLED"))).toEqual({
kind: "cancellation",
formatted: "CIAO PROBING CANCELLED",
});
@@ -13,7 +13,7 @@ describe("bonjour-ciao", () => {
it("classifies ciao interface assertions separately from side effects", () => {
expect(
classifyCiaoUnhandledRejection(
classifyCiaoProcessError(
new Error("Reached illegal state! IPV4 address change from defined to undefined!"),
),
).toEqual({
@@ -24,7 +24,7 @@ describe("bonjour-ciao", () => {
it("classifies ciao interface assertions using changed wording", () => {
expect(
classifyCiaoUnhandledRejection(
classifyCiaoProcessError(
new Error("Reached illegal state! IPv4 address changed from undefined to defined!"),
),
).toEqual({
@@ -35,7 +35,7 @@ describe("bonjour-ciao", () => {
it("classifies ciao netmask assertions separately from side effects", () => {
expect(
classifyCiaoUnhandledRejection(
classifyCiaoProcessError(
Object.assign(
new Error(
"IP address version must match. Netmask cannot have a version different from the address!",
@@ -52,7 +52,7 @@ describe("bonjour-ciao", () => {
it("classifies ciao self-probe races separately from side effects", () => {
expect(
classifyCiaoUnhandledRejection(
classifyCiaoProcessError(
new Error(
"Can't probe for a service which is announced already. Received announcing for service OpenClaw Gateway._openclaw._tcp.local.",
),
@@ -65,18 +65,18 @@ describe("bonjour-ciao", () => {
});
it("suppresses ciao announcement cancellation rejections", () => {
expect(ignoreCiaoUnhandledRejection(new Error("Ciao announcement cancelled by shutdown"))).toBe(
true,
expect(classifyCiaoProcessError(new Error("Ciao announcement cancelled by shutdown"))).not.toBe(
null,
);
});
it("suppresses ciao probing cancellation rejections", () => {
expect(ignoreCiaoUnhandledRejection(new Error("CIAO PROBING CANCELLED"))).toBe(true);
expect(classifyCiaoProcessError(new Error("CIAO PROBING CANCELLED"))).not.toBe(null);
});
it("suppresses wrapped ciao cancellation rejections", () => {
expect(
classifyCiaoUnhandledRejection({
classifyCiaoProcessError({
reason: new Error("CIAO ANNOUNCEMENT CANCELLED"),
}),
).toEqual({
@@ -87,7 +87,7 @@ describe("bonjour-ciao", () => {
it("suppresses aggregate ciao assertion rejections", () => {
expect(
classifyCiaoUnhandledRejection(
classifyCiaoProcessError(
new AggregateError([
Object.assign(
new Error("Reached illegal state! IPV4 address change from defined to undefined!"),
@@ -103,7 +103,7 @@ describe("bonjour-ciao", () => {
});
it("suppresses lower-case string cancellation reasons too", () => {
expect(ignoreCiaoUnhandledRejection("ciao announcement cancelled during cleanup")).toBe(true);
expect(classifyCiaoProcessError("ciao announcement cancelled during cleanup")).not.toBe(null);
});
it("suppresses ciao interface assertion rejections as non-fatal", () => {
@@ -112,7 +112,7 @@ describe("bonjour-ciao", () => {
{ name: "AssertionError" },
);
expect(ignoreCiaoUnhandledRejection(error)).toBe(true);
expect(classifyCiaoProcessError(error)).not.toBe(null);
});
it("suppresses ciao netmask assertion errors as non-fatal", () => {
@@ -123,7 +123,7 @@ describe("bonjour-ciao", () => {
{ name: "AssertionError" },
);
expect(ignoreCiaoUnhandledRejection(error)).toBe(true);
expect(classifyCiaoProcessError(error)).not.toBe(null);
});
it("classifies networkInterfaces SystemError failures (restricted sandboxes)", () => {
@@ -131,7 +131,7 @@ describe("bonjour-ciao", () => {
new Error("A system error occurred: uv_interface_addresses returned Unknown system error 1"),
{ name: "SystemError" },
);
expect(classifyCiaoUnhandledRejection(err)).toEqual({
expect(classifyCiaoProcessError(err)).toEqual({
kind: "interface-enumeration-failure",
formatted:
"SystemError: A system error occurred: uv_interface_addresses returned Unknown system error 1",
@@ -144,10 +144,10 @@ describe("bonjour-ciao", () => {
{ name: "SystemError" },
);
const wrapper = new Error("ciao NetworkManager init failed", { cause: inner });
expect(ignoreCiaoUnhandledRejection(wrapper)).toBe(true);
expect(classifyCiaoProcessError(wrapper)).not.toBe(null);
});
it("keeps unrelated rejections visible", () => {
expect(ignoreCiaoUnhandledRejection(new Error("boom"))).toBe(false);
expect(classifyCiaoProcessError(new Error("boom"))).toBe(null);
});
});

View File

@@ -55,15 +55,3 @@ export function classifyCiaoProcessError(reason: unknown): CiaoProcessErrorClass
}
return null;
}
/**
* Backward-compatible alias for unhandled-rejection classification.
*
* @deprecated Use classifyCiaoProcessError.
*/
export const classifyCiaoUnhandledRejection = classifyCiaoProcessError;
/** Return whether a ciao unhandled rejection is known and ignorable. */
export function ignoreCiaoUnhandledRejection(reason: unknown): boolean {
return classifyCiaoProcessError(reason) !== null;
}

View File

@@ -36,12 +36,133 @@ function createElementProgram(): Command {
return program;
}
function getLastActionBody(): Record<string, unknown> | undefined {
return (mocks.callBrowserRequest.mock.calls.at(-1)?.[1] as { body?: Record<string, unknown> })
?.body;
}
describe("browser element commands", () => {
beforeEach(() => {
mocks.callBrowserRequest.mockClear();
getBrowserCliRuntimeCapture().resetRuntimeCapture();
});
it.each([
{
name: "click",
argv: [
"browser",
"click",
" ref-1 ",
"--target-id",
"tab-1",
"--double",
"--button",
"right",
"--modifiers",
"Shift, Alt",
],
expectedBody: {
kind: "click",
ref: "ref-1",
targetId: "tab-1",
doubleClick: true,
button: "right",
modifiers: ["Shift", "Alt"],
},
},
{
name: "click-coords",
argv: [
"browser",
"click-coords",
"12.5",
"42",
"--target-id",
"tab-2",
"--double",
"--button",
"middle",
"--delay-ms",
"25",
],
expectedBody: {
kind: "clickCoords",
x: 12.5,
y: 42,
targetId: "tab-2",
doubleClick: true,
button: "middle",
delayMs: 25,
},
},
{
name: "type",
argv: ["browser", "type", "input-1", "hello", "--submit", "--slowly", "--target-id", "tab-2"],
expectedBody: {
kind: "type",
ref: "input-1",
text: "hello",
submit: true,
slowly: true,
targetId: "tab-2",
},
},
{
name: "press",
argv: ["browser", "press", "Enter", "--target-id", "tab-3"],
expectedBody: { kind: "press", key: "Enter", targetId: "tab-3" },
},
{
name: "hover",
argv: ["browser", "hover", "node-1", "--target-id", "tab-4"],
expectedBody: { kind: "hover", ref: "node-1", targetId: "tab-4" },
},
{
name: "scrollintoview",
argv: ["browser", "scrollintoview", "node-2", "--target-id", "tab-5"],
expectedBody: { kind: "scrollIntoView", ref: "node-2", targetId: "tab-5" },
},
{
name: "drag",
argv: ["browser", "drag", "start-1", "end-1", "--target-id", "tab-6"],
expectedBody: {
kind: "drag",
startRef: "start-1",
endRef: "end-1",
targetId: "tab-6",
},
},
{
name: "select",
argv: ["browser", "select", "select-1", "alpha", "beta", "--target-id", "tab-7"],
expectedBody: {
kind: "select",
ref: "select-1",
values: ["alpha", "beta"],
targetId: "tab-7",
},
},
])("sends the expected $name action body", async ({ argv, expectedBody }) => {
const program = createElementProgram();
await program.parseAsync(argv, { from: "user" });
expect(getLastActionBody()).toMatchObject(expectedBody);
});
it("rejects a blank required ref before dispatch", async () => {
const program = createElementProgram();
await expect(program.parseAsync(["browser", "click", " "], { from: "user" })).rejects.toThrow(
"__exit__:1",
);
const capture = getBrowserCliRuntimeCapture();
expect(capture.runtimeErrors.join("\n")).toContain("ref is required");
expect(mocks.callBrowserRequest).not.toHaveBeenCalled();
});
it("rejects non-decimal coordinate values before dispatch", async () => {
const program = createElementProgram();

View File

@@ -31,6 +31,10 @@ vi.spyOn(cliCoreApiModule.defaultRuntime, "writeJson").mockImplementation(
);
vi.spyOn(cliCoreApiModule.defaultRuntime, "error").mockImplementation(browserCliRuntime.error);
vi.spyOn(cliCoreApiModule.defaultRuntime, "exit").mockImplementation(browserCliRuntime.exit);
vi.spyOn(cliCoreApiModule, "resolveExistingUploadPaths").mockResolvedValue({
ok: true,
paths: ["/tmp/openclaw/uploads/a.pdf", "/tmp/openclaw/uploads/b.pdf"],
});
const { registerBrowserActionInputCommands } = await import("./register.js");
@@ -47,10 +51,51 @@ function getLastRequestOptions(): { timeoutMs?: number } | undefined {
describe("browser action input file/download commands", () => {
beforeEach(() => {
mocks.callBrowserRequest.mockClear();
vi.mocked(cliCoreApiModule.resolveExistingUploadPaths).mockClear();
getBrowserCliRuntimeCapture().resetRuntimeCapture();
getBrowserCliRuntime().exit.mockImplementation(() => {});
});
it("arms uploads with normalized paths and element targeting options", async () => {
const program = createActionInputProgram();
await program.parseAsync(
[
"browser",
"upload",
"/tmp/openclaw/uploads/a.pdf",
"media://inbound/b",
"--input-ref",
"file-input",
"--element",
"input[type=file]",
"--target-id",
"tab-1",
"--timeout-ms",
"45000",
],
{ from: "user" },
);
expect(cliCoreApiModule.resolveExistingUploadPaths).toHaveBeenCalledWith({
requestedPaths: ["/tmp/openclaw/uploads/a.pdf", "media://inbound/b"],
});
const request = mocks.callBrowserRequest.mock.calls.at(-1)?.[1] as
| { path?: string; body?: Record<string, unknown> }
| undefined;
expect(request).toMatchObject({
path: "/hooks/file-chooser",
body: {
paths: ["/tmp/openclaw/uploads/a.pdf", "/tmp/openclaw/uploads/b.pdf"],
inputRef: "file-input",
element: "input[type=file]",
targetId: "tab-1",
timeoutMs: 45000,
},
});
expect(getLastRequestOptions()?.timeoutMs).toBeGreaterThan(45000);
});
it("keeps the outer waitfordownload request open for the advertised default wait", async () => {
const program = createActionInputProgram();

View File

@@ -36,6 +36,43 @@ function createActionInputProgram(): Command {
return program;
}
function getLastActionBody(): Record<string, unknown> | undefined {
return (mocks.callBrowserRequest.mock.calls.at(-1)?.[1] as { body?: Record<string, unknown> })
?.body;
}
describe("browser action input fill command", () => {
beforeEach(() => {
mocks.callBrowserRequest.mockClear();
getBrowserCliRuntimeCapture().resetRuntimeCapture();
});
it("sends normalized fill fields and target id to the act route", async () => {
const program = createActionInputProgram();
await program.parseAsync(
[
"browser",
"fill",
"--fields",
'[{"ref":"name","value":"Ada"},{"ref":"enabled","value":true}]',
"--target-id",
"tab-1",
],
{ from: "user" },
);
expect(getLastActionBody()).toMatchObject({
kind: "fill",
fields: [
{ ref: "name", type: "text", value: "Ada" },
{ ref: "enabled", type: "text", value: true },
],
targetId: "tab-1",
});
});
});
describe("browser action input wait command", () => {
beforeEach(() => {
mocks.callBrowserRequest.mockClear();
@@ -99,6 +136,31 @@ describe("browser action input evaluate command", () => {
getBrowserCliRuntimeCapture().resetRuntimeCapture();
});
it("sends evaluate function, ref, and target id to the act route", async () => {
const program = createActionInputProgram();
await program.parseAsync(
[
"browser",
"evaluate",
"--fn",
"el => el.textContent",
"--ref",
"button-1",
"--target-id",
"tab-2",
],
{ from: "user" },
);
expect(getLastActionBody()).toMatchObject({
kind: "evaluate",
fn: "el => el.textContent",
ref: "button-1",
targetId: "tab-2",
});
});
it("passes timeout-ms through to the evaluate action and outer request", async () => {
const program = createActionInputProgram();

View File

@@ -2,6 +2,7 @@
import { Command } from "commander";
import { beforeEach, describe, expect, it, vi } from "vitest";
import * as browserCliResizeModule from "../browser-cli-resize.js";
import * as browserCliSharedModule from "../browser-cli-shared.js";
import {
createBrowserProgram,
getBrowserCliRuntime,
@@ -10,9 +11,17 @@ import {
import * as cliCoreApiModule from "../core-api.js";
const mocks = vi.hoisted(() => ({
callBrowserRequest: vi.fn<
(
opts?: unknown,
req?: unknown,
extra?: { timeoutMs?: number },
) => Promise<Record<string, unknown>>
>(async () => ({ url: "https://example.test/landing" })),
runBrowserResizeWithOutput: vi.fn(async () => {}),
}));
vi.spyOn(browserCliSharedModule, "callBrowserRequest").mockImplementation(mocks.callBrowserRequest);
vi.spyOn(browserCliResizeModule, "runBrowserResizeWithOutput").mockImplementation(
mocks.runBrowserResizeWithOutput,
);
@@ -34,10 +43,51 @@ function createNavigationProgram(): Command {
describe("browser navigation commands", () => {
beforeEach(() => {
mocks.callBrowserRequest.mockClear();
mocks.runBrowserResizeWithOutput.mockClear();
getBrowserCliRuntimeCapture().resetRuntimeCapture();
});
it("sends navigate requests with the URL and target id", async () => {
const program = createNavigationProgram();
await program.parseAsync(
["browser", "navigate", "https://example.test/page", "--target-id", "tab-1"],
{ from: "user" },
);
const request = mocks.callBrowserRequest.mock.calls.at(-1)?.[1] as
| { method?: string; path?: string; body?: Record<string, unknown> }
| undefined;
const options = mocks.callBrowserRequest.mock.calls.at(-1)?.[2] as
| { timeoutMs?: number }
| undefined;
expect(request).toMatchObject({
method: "POST",
path: "/navigate",
body: { url: "https://example.test/page", targetId: "tab-1" },
});
expect(options?.timeoutMs).toBe(20000);
});
it("passes normalized resize dimensions and target id to the resize helper", async () => {
const program = createNavigationProgram();
await program.parseAsync(["browser", "resize", "1024", "768", "--target-id", "tab-2"], {
from: "user",
});
expect(mocks.runBrowserResizeWithOutput).toHaveBeenCalledWith(
expect.objectContaining({
width: 1024,
height: 768,
targetId: "tab-2",
timeoutMs: 20000,
successMessage: "resized to 1024x768",
}),
);
});
it("rejects non-decimal resize dimensions before dispatch", async () => {
const program = createNavigationProgram();

View File

@@ -152,10 +152,10 @@
]
},
"url": { "type": "string" },
"authToken": { "type": "string" },
"authToken": { "type": ["string", "object"] },
"headers": {
"type": "object",
"additionalProperties": { "type": "string" }
"additionalProperties": { "type": ["string", "object"] }
},
"clearEnv": {
"type": "array",
@@ -254,6 +254,14 @@
}
}
},
"configContracts": {
"secretInputs": {
"paths": [
{ "path": "appServer.authToken", "expected": "string" },
{ "path": "appServer.headers.*", "expected": "string" }
]
}
},
"uiHints": {
"codexDynamicToolsLoading": {
"label": "Dynamic Tools Loading",
@@ -382,6 +390,7 @@
"appServer.headers": {
"label": "Headers",
"help": "Additional headers sent to the WebSocket app-server.",
"sensitive": true,
"advanced": true
},
"appServer.clearEnv": {

View File

@@ -28,6 +28,10 @@ function resolveRuntimeForTest(params: RuntimeOptionsParams = {}) {
return resolveCodexAppServerRuntimeOptions({ env: {}, requirementsToml: null, ...params });
}
function envRef(id: string) {
return { source: "env" as const, provider: "default", id };
}
function requireRecord(value: unknown, label: string): Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`Expected ${label}`);
@@ -413,6 +417,65 @@ describe("Codex app-server config", () => {
});
});
it("passes resolved app-server SecretInput strings through to auth token and headers", () => {
const runtime = resolveRuntimeForTest({
pluginConfig: {
appServer: {
transport: "websocket",
url: "wss://codex-app-server.example.internal/ws",
authToken: " resolved-capability-token ",
headers: {
" x-codex-client-session-token ": " resolved-session-token ",
Authorization: " Bearer explicit-token ",
},
},
},
});
expectFields(runtime.start, "runtime start", {
authToken: "resolved-capability-token",
headers: {
"x-codex-client-session-token": "resolved-session-token",
Authorization: "Bearer explicit-token",
},
});
});
it("rejects unresolved app-server auth token SecretRefs at runtime option resolution", () => {
expect(() =>
resolveRuntimeForTest({
pluginConfig: {
appServer: {
transport: "websocket",
url: "wss://codex-app-server.example.internal/ws",
authToken: envRef("CODEX_APP_SERVER_TOKEN"),
},
},
}),
).toThrow(
'plugins.entries.codex.config.appServer.authToken: unresolved SecretRef "env:default:CODEX_APP_SERVER_TOKEN"',
);
});
it("rejects unresolved app-server header SecretRefs at runtime option resolution", () => {
expect(() =>
resolveRuntimeForTest({
pluginConfig: {
appServer: {
transport: "websocket",
url: "wss://codex-app-server.example.internal/ws",
authToken: "capability-token",
headers: {
"x-codex-client-session-token": envRef("CODEX_CLIENT_SESSION_TOKEN"),
},
},
},
}),
).toThrow(
'plugins.entries.codex.config.appServer.headers.x-codex-client-session-token: unresolved SecretRef "env:default:CODEX_CLIENT_SESSION_TOKEN"',
);
});
it("treats IPv6 loopback websocket app-servers as local loopback", () => {
const runtime = resolveRuntimeForTest({
pluginConfig: {
@@ -2314,6 +2377,47 @@ allowed_sandbox_modes = ["read-only", "workspace-write"]
expect(second).not.toContain("sk-second");
});
it("derives distinct shared-client keys for distinct headers without exposing them", () => {
const first = codexAppServerStartOptionsKey({
transport: "websocket",
command: "codex",
args: [],
url: "ws://127.0.0.1:39175",
headers: {
Authorization: "Bearer first",
"x-codex-client-session-token": "session-first",
},
});
const second = codexAppServerStartOptionsKey({
transport: "websocket",
command: "codex",
args: [],
url: "ws://127.0.0.1:39175",
headers: {
Authorization: "Bearer second",
"x-codex-client-session-token": "session-second",
},
});
expect(first).not.toEqual(second);
expect(
codexAppServerStartOptionsKey({
transport: "websocket",
command: "codex",
args: [],
url: "ws://127.0.0.1:39175",
headers: {
Authorization: "Bearer first",
"x-codex-client-session-token": "session-first",
},
}),
).toEqual(first);
expect(first).not.toContain("Bearer first");
expect(first).not.toContain("session-first");
expect(second).not.toContain("Bearer second");
expect(second).not.toContain("session-second");
});
it("keeps secret-derived shared-client keys stable across module reloads", async () => {
const startOptions = {
transport: "websocket" as const,

View File

@@ -13,6 +13,11 @@ import {
} from "openclaw/plugin-sdk/exec-approvals-runtime";
import { resolvePositiveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
import { normalizeAgentId } from "openclaw/plugin-sdk/routing";
import {
buildSecretInputSchema,
normalizeResolvedSecretInputString,
type SecretInput,
} from "openclaw/plugin-sdk/secret-input";
import { normalizeTrimmedStringList } from "openclaw/plugin-sdk/string-coerce-runtime";
import { detectWindowsSpawnCommandInlineArgs } from "openclaw/plugin-sdk/windows-spawn";
import { z } from "zod";
@@ -211,8 +216,8 @@ export type CodexPluginConfig = {
command?: string;
args?: string[] | string;
url?: string;
authToken?: string;
headers?: Record<string, string>;
authToken?: SecretInput;
headers?: Record<string, SecretInput>;
clearEnv?: string[];
remoteWorkspaceRoot?: string;
codeModeOnly?: boolean;
@@ -294,6 +299,7 @@ const DEFAULT_CODEX_COMPUTER_USE_MARKETPLACE_DISCOVERY_TIMEOUT_MS = 60_000;
const DEFAULT_CODEX_APP_SERVER_NETWORK_PROXY_PROFILE_PREFIX = "openclaw-network";
const codexAppServerTransportSchema = z.enum(["stdio", "websocket"]);
const SecretInputSchema = buildSecretInputSchema();
const codexAppServerPolicyModeSchema = z.enum(["yolo", "guardian"]);
const codexAppServerApprovalPolicySchema = z.enum([
"never",
@@ -387,8 +393,8 @@ const codexPluginConfigSchema = z
command: z.string().optional(),
args: z.union([z.array(z.string()), z.string()]).optional(),
url: z.string().optional(),
authToken: z.string().optional(),
headers: z.record(z.string(), z.string()).optional(),
authToken: SecretInputSchema.optional(),
headers: z.record(z.string(), SecretInputSchema).optional(),
clearEnv: z.array(z.string()).optional(),
remoteWorkspaceRoot: codexAppServerRemoteWorkspaceRootSchema.optional(),
codeModeOnly: z.boolean().optional(),
@@ -531,7 +537,10 @@ export function resolveCodexAppServerRuntimeOptions(
const args = resolveArgs(config.args, env.OPENCLAW_CODEX_APP_SERVER_ARGS);
const headers = normalizeHeaders(config.headers);
const clearEnv = normalizeStringList(config.clearEnv);
const authToken = readNonEmptyString(config.authToken);
const authToken = normalizeCodexAppServerSecretInput({
value: config.authToken,
path: "plugins.entries.codex.config.appServer.authToken",
});
const url = readNonEmptyString(config.url);
const connectionClass = inferCodexAppServerConnectionClass({ transport, url });
const remoteAppsSubstrate: CodexAppServerRemoteAppsSubstrate = "preconfigured";
@@ -868,9 +877,9 @@ export function codexAppServerStartOptionsKey(
args: options.args,
url: options.url ?? null,
authToken: hashSecretForKey(options.authToken, "authToken"),
headers: Object.entries(options.headers).toSorted(([left], [right]) =>
left.localeCompare(right),
),
headers: Object.entries(options.headers)
.toSorted(([left], [right]) => left.localeCompare(right))
.map(([key, value]) => [key, hashSecretForKey(value, `header:${key}`)]),
env: Object.entries(options.env ?? {})
.toSorted(([left], [right]) => left.localeCompare(right))
.map(([key, value]) => [key, hashSecretForKey(value, `env:${key}`)]),
@@ -2037,11 +2046,27 @@ function normalizeHeaders(value: unknown): Record<string, string> {
}
return Object.fromEntries(
Object.entries(value)
.map(([key, child]) => [key.trim(), readNonEmptyString(child)] as const)
.map(
([key, child]) =>
[
key.trim(),
normalizeCodexAppServerSecretInput({
value: child,
path: `plugins.entries.codex.config.appServer.headers.${key}`,
}),
] as const,
)
.filter((entry): entry is readonly [string, string] => Boolean(entry[0] && entry[1])),
);
}
function normalizeCodexAppServerSecretInput(params: {
value: unknown;
path: string;
}): string | undefined {
return normalizeResolvedSecretInputString(params);
}
function normalizeStringList(value: unknown): string[] {
return normalizeTrimmedStringList(value);
}

View File

@@ -2,6 +2,7 @@
import type { AgentMessage } from "openclaw/plugin-sdk/agent-core";
import { describe, expect, it } from "vitest";
import {
CODEX_TURN_START_TEXT_INPUT_MAX_CHARS,
fitCodexProjectedContextForTurnStart,
projectContextEngineAssemblyForCodex,
resolveCodexContextEngineProjectionMaxChars,
@@ -226,6 +227,92 @@ describe("projectContextEngineAssemblyForCodex", () => {
expect(fitted).not.toContain("old context");
});
it("bounds output when the non-context text alone exceeds the turn limit", () => {
// A large older-context header prefix pushes before + after over maxChars
// while the trailing user request stays small enough to keep its label.
const before = `OpenClaw assembled context for this turn:\n${"prefix ".repeat(120)}`;
const context = "older context ".repeat(40);
const prompt = `urgent request ${"q".repeat(120)}`;
const after = `\n</conversation_context>\n\nCurrent user request:\n${prompt}`;
const promptText = `${before}${context}${after}`;
const maxChars = 420;
// before + after already exceed maxChars, so the context budget is non-positive.
expect(before.length + after.length).toBeGreaterThan(maxChars);
const fitted = fitCodexProjectedContextForTurnStart({
promptText,
contextRange: { start: before.length, end: before.length + context.length },
maxChars,
});
expect(fitted.length).toBeLessThanOrEqual(maxChars);
// The user's actual request is the priority tail and must survive truncation.
expect(fitted).toContain("Current user request:");
expect(fitted.endsWith("q".repeat(40))).toBe(true);
// The dropped older context is reported, not silently lost.
expect(fitted).toContain("[truncated ");
});
it("bounds output for a large request under the default Codex turn limit", () => {
const maxChars = CODEX_TURN_START_TEXT_INPUT_MAX_CHARS;
// A large assembled header prefix already over the cap forces the
// non-positive context budget on the real default limit (1 << 20).
const before = `header\n${"older history ".repeat(90_000)}`;
const context = "x".repeat(2_000);
const prompt = `urgent request ${"u".repeat(2_000)}`;
const after = `\n</conversation_context>\n\nCurrent user request:\n${prompt}`;
const promptText = `${before}${context}${after}`;
expect(before.length + after.length).toBeGreaterThan(maxChars);
const fitted = fitCodexProjectedContextForTurnStart({
promptText,
contextRange: { start: before.length, end: before.length + context.length },
// maxChars omitted -> defaults to CODEX_TURN_START_TEXT_INPUT_MAX_CHARS.
});
expect(fitted.length).toBeLessThanOrEqual(maxChars);
// The user request is the priority tail and survives even though the older
// header text is truncated to satisfy the limit.
expect(fitted).toContain("Current user request:");
expect(fitted.endsWith("u".repeat(1_000))).toBe(true);
});
it("never splits a UTF-16 surrogate pair at the truncation boundary", () => {
// Drive the non-positive-budget path with an emoji (surrogate pair) sitting
// across the kept-tail cut. A naive code-unit slice would orphan the low
// surrogate into U+FFFD; the boundary must stay on a whole code point.
const before = `OpenClaw assembled context for this turn:\n${"H".repeat(300)}`;
const context = "older context ".repeat(20);
// Emoji immediately before the user text so the cut can fall mid-pair.
const prompt = `\u{1F600}${"U".repeat(60)}`;
const after = `\n</conversation_context>\n\nCurrent user request:\n${prompt}`;
const promptText = `${before}${context}${after}`;
const contextRange = { start: before.length, end: before.length + context.length };
// Sweep cap sizes around the cut so the test is not brittle to marker length;
// at least one value lands the boundary inside the surrogate pair.
for (let maxChars = 90; maxChars <= 140; maxChars += 1) {
const fitted = fitCodexProjectedContextForTurnStart({ promptText, contextRange, maxChars });
expect(fitted.length).toBeLessThanOrEqual(maxChars);
// U+FFFD only appears when a lone surrogate is rendered, i.e. a split pair.
expect(fitted).not.toContain("<22>");
// Any surviving emoji must be the complete pair, not a lone low surrogate.
for (let i = 0; i < fitted.length; i += 1) {
const code = fitted.charCodeAt(i);
const isLowSurrogate = code >= 0xdc00 && code <= 0xdfff;
const isHighSurrogate = code >= 0xd800 && code <= 0xdbff;
if (isLowSurrogate) {
const prev = fitted.charCodeAt(i - 1);
expect(prev >= 0xd800 && prev <= 0xdbff).toBe(true);
}
if (isHighSurrogate) {
const next = fitted.charCodeAt(i + 1);
expect(next >= 0xdc00 && next <= 0xdfff).toBe(true);
}
}
}
});
it("keeps the old conservative cap when no runtime budget is available", () => {
expect(resolveCodexContextEngineProjectionMaxChars({})).toBe(24_000);
expect(resolveCodexContextEngineProjectionMaxChars({ contextTokenBudget: 0 })).toBe(24_000);

View File

@@ -139,8 +139,16 @@ export function fitCodexProjectedContextForTurnStart(params: {
const context = params.promptText.slice(range.start, range.end);
const afterContext = params.promptText.slice(range.end);
const contextBudget = maxChars - beforeContext.length - afterContext.length;
const fittedContext = truncateOlderContext(context, contextBudget);
return `${beforeContext}${fittedContext}${afterContext}`;
if (contextBudget > 0) {
const fittedContext = truncateOlderContext(context, contextBudget);
return `${beforeContext}${fittedContext}${afterContext}`;
}
// The header plus the trailing user request already fill the limit, so the
// older context drops entirely and the remaining text must still be bounded;
// otherwise Codex app-server rejects the turn for exceeding
// MAX_USER_INPUT_TEXT_CHARS. truncateOlderContext keeps the tail, preserving
// the user's actual request over the older header text.
return truncateOlderContext(`${beforeContext}${afterContext}`, maxChars);
}
function normalizeProjectedContextRange(
@@ -457,5 +465,20 @@ function truncateOlderContext(text: string, maxChars: number): string {
return marker.slice(0, maxChars);
}
tailChars = maxChars - marker.length;
return `${marker}${text.slice(text.length - tailChars).trimStart()}`;
return `${marker}${sliceTailFromCodePointBoundary(text, tailChars).trimStart()}`;
}
// Keep the kept tail at a code-point boundary so a UTF-16 surrogate pair is
// never split at the cut: a tail start that lands on a low surrogate would
// orphan it into U+FFFD, corrupting the first character. Dropping that unit
// stays within maxChars (it only removes a char), so the bound still holds.
function sliceTailFromCodePointBoundary(text: string, tailChars: number): string {
let start = text.length - tailChars;
if (start > 0 && start < text.length) {
const code = text.charCodeAt(start);
if (code >= 0xdc00 && code <= 0xdfff) {
start += 1;
}
}
return text.slice(start);
}

View File

@@ -2,13 +2,17 @@
import type { FileDiffMetadata } from "@pierre/diffs";
import { describe, expect, it } from "vitest";
import {
filterSupportedLanguageHints,
normalizeDiffViewerPayloadLanguages,
normalizeSupportedLanguageHint,
} from "./language-hints.js";
describe("filterSupportedLanguageHints", () => {
async function normalizeHints(values: readonly string[], options = {}) {
return await Promise.all(values.map((value) => normalizeSupportedLanguageHint(value, options)));
}
describe("normalizeSupportedLanguageHint", () => {
it("keeps supported languages", async () => {
await expect(filterSupportedLanguageHints(["typescript", "cpp", "text"])).resolves.toEqual([
await expect(normalizeHints(["typescript", "cpp", "text"])).resolves.toEqual([
"typescript",
"cpp",
"text",
@@ -17,7 +21,7 @@ describe("filterSupportedLanguageHints", () => {
it("normalizes common aliases to base viewer languages", async () => {
await expect(
filterSupportedLanguageHints(["ts", "c++", "c#", "bash", "dockerfile", "rb", "kt", "ps1"]),
normalizeHints(["ts", "c++", "c#", "bash", "dockerfile", "rb", "kt", "ps1"]),
).resolves.toEqual([
"typescript",
"cpp",
@@ -32,7 +36,7 @@ describe("filterSupportedLanguageHints", () => {
it("keeps mainstream languages in the base viewer without the language pack", async () => {
await expect(
filterSupportedLanguageHints([
normalizeHints([
"ruby",
"swift",
"kotlin",
@@ -57,23 +61,24 @@ describe("filterSupportedLanguageHints", () => {
});
it("drops uncommon languages without the language pack", async () => {
await expect(filterSupportedLanguageHints(["abap"])).resolves.toEqual(["text"]);
await expect(normalizeSupportedLanguageHint("abap")).resolves.toBeUndefined();
});
it("keeps uncommon languages when the language pack is available", async () => {
await expect(
filterSupportedLanguageHints(["abap"], { languagePackAvailable: true }),
).resolves.toEqual(["abap"]);
normalizeSupportedLanguageHint("abap", { languagePackAvailable: true }),
).resolves.toBe("abap");
});
it("drops invalid languages and falls back to text", async () => {
await expect(filterSupportedLanguageHints(["not-a-real-language"])).resolves.toEqual(["text"]);
it("drops invalid languages", async () => {
await expect(normalizeSupportedLanguageHint("not-a-real-language")).resolves.toBeUndefined();
});
it("keeps valid languages when invalid hints are mixed in", async () => {
await expect(
filterSupportedLanguageHints(["typescript", "not-a-real-language"]),
).resolves.toEqual(["typescript"]);
await expect(normalizeHints(["typescript", "not-a-real-language"])).resolves.toEqual([
"typescript",
undefined,
]);
});
});

View File

@@ -57,13 +57,6 @@ export async function normalizeSupportedLanguageHint(
}
}
export async function filterSupportedLanguageHints(
values: Iterable<string>,
options: { languagePackAvailable?: boolean } = {},
): Promise<SupportedLanguages[]> {
return normalizeSupportedLanguageHints(values, { fallbackToText: true, ...options });
}
async function normalizeSupportedLanguageHints(
values: Iterable<string>,
options: { fallbackToText: boolean; languagePackAvailable?: boolean },

View File

@@ -55,16 +55,17 @@ const viewerPayload = JSON.stringify({
unsafeCSS: "",
},
langs: ["text"],
oldFile: { fileName: "a.ts", lang: "text", content: "old" },
newFile: { fileName: "a.ts", lang: "text", content: "new" },
oldFile: { name: "a.ts", lang: "text", contents: "old" },
newFile: { name: "a.ts", lang: "text", contents: "new" },
});
function renderCard(): void {
function renderCard(payloadOverride?: string): void {
const payload = payloadOverride ?? viewerPayload;
document.body.insertAdjacentHTML(
"beforeend",
`<section class="oc-diff-card">
<div data-openclaw-diff-host></div>
<script type="application/json" data-openclaw-diff-payload>${viewerPayload}</script>
<script type="application/json" data-openclaw-diff-payload>${payload}</script>
</section>`,
);
}
@@ -172,3 +173,300 @@ describe("hydrateViewer", () => {
warn.mockRestore();
});
});
describe("viewerState initialization", () => {
beforeEach(() => {
document.body.innerHTML = "";
delete document.documentElement.dataset.openclawDiffsError;
delete document.documentElement.dataset.openclawDiffsReady;
delete document.body.dataset.theme;
vi.clearAllMocks();
});
it("seeds viewerState from firstPayload options and syncs document theme", async () => {
const customPayload = JSON.stringify({
prerenderedHTML: "<div>diff</div>",
options: {
theme: { light: "pierre-light", dark: "pierre-dark" },
diffStyle: "split",
diffIndicators: "bars",
disableLineNumbers: false,
expandUnchanged: false,
themeType: "light",
backgroundEnabled: false,
overflow: "scroll",
unsafeCSS: "",
},
langs: ["text"],
oldFile: { name: "a.ts", lang: "text", contents: "old" },
newFile: { name: "a.ts", lang: "text", contents: "new" },
});
renderCard(customPayload);
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
expect(document.body.dataset.theme).toBe("light");
const opts = fileDiffSetOptionsMock.mock.calls[0]?.[0] as Record<string, unknown>;
expect(opts.diffStyle).toBe("split");
expect(opts.themeType).toBe("light");
expect(opts.overflow).toBe("scroll");
expect(opts.disableBackground).toBe(true);
});
it("defaults viewerState to dark/unified/wrap/background when firstPayload uses defaults", async () => {
renderCard();
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
expect(document.body.dataset.theme).toBe("dark");
const opts = fileDiffSetOptionsMock.mock.calls[0]?.[0] as Record<string, unknown>;
expect(opts.diffStyle).toBe("unified");
expect(opts.themeType).toBe("dark");
expect(opts.overflow).toBe("wrap");
expect(opts.disableBackground).toBe(false);
});
it("preloadHighlighter receives merged language set from all cards", async () => {
const payload1 = JSON.stringify({
prerenderedHTML: "<div>diff1</div>",
options: {
theme: { light: "pierre-light", dark: "pierre-dark" },
diffStyle: "unified",
diffIndicators: "bars",
disableLineNumbers: false,
expandUnchanged: false,
themeType: "dark",
backgroundEnabled: true,
overflow: "wrap",
unsafeCSS: "",
},
langs: ["typescript"],
oldFile: { name: "a.ts", lang: "typescript", contents: "old" },
newFile: { name: "a.ts", lang: "typescript", contents: "new" },
});
const payload2 = JSON.stringify({
prerenderedHTML: "<div>diff2</div>",
options: {
theme: { light: "pierre-light", dark: "pierre-dark" },
diffStyle: "unified",
diffIndicators: "bars",
disableLineNumbers: false,
expandUnchanged: false,
themeType: "dark",
backgroundEnabled: true,
overflow: "wrap",
unsafeCSS: "",
},
langs: ["python"],
oldFile: { name: "b.py", lang: "python", contents: "old" },
newFile: { name: "b.py", lang: "python", contents: "new" },
});
renderCard(payload1);
renderCard(payload2);
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
const preloadArg = (preloadHighlighterMock.mock.calls as unknown[][])[0]?.[0] as
| { langs: string[]; themes: string[] }
| undefined;
expect(preloadArg).toBeDefined();
expect(preloadArg!.langs).toContain("typescript");
expect(preloadArg!.langs).toContain("python");
expect(preloadArg!.themes).toEqual(["pierre-light", "pierre-dark"]);
});
});
describe("toolbar button toggles", () => {
beforeEach(() => {
document.body.innerHTML = "";
delete document.body.dataset.theme;
vi.clearAllMocks();
});
it("layout toggle switches between unified and split", async () => {
renderCard();
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
const opts1 = fileDiffSetOptionsMock.mock.calls[0]?.[0] as Record<string, unknown>;
expect(opts1.diffStyle).toBe("unified");
const renderHeaderMetadata = opts1.renderHeaderMetadata as () => HTMLElement;
const toolbar = renderHeaderMetadata();
const buttons = toolbar.querySelectorAll("button");
buttons[0].click();
expect(fileDiffRerenderMock).toHaveBeenCalled();
const opts2 = fileDiffSetOptionsMock.mock.calls[
fileDiffSetOptionsMock.mock.calls.length - 1
]?.[0] as Record<string, unknown>;
expect(opts2.diffStyle).toBe("split");
});
it("theme toggle switches between dark and light", async () => {
renderCard();
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
const opts1 = fileDiffSetOptionsMock.mock.calls[0]?.[0] as Record<string, unknown>;
expect(opts1.themeType).toBe("dark");
const renderHeaderMetadata = opts1.renderHeaderMetadata as () => HTMLElement;
const toolbar = renderHeaderMetadata();
const buttons = toolbar.querySelectorAll("button");
buttons[3].click();
const lastOpts = fileDiffSetOptionsMock.mock.calls[
fileDiffSetOptionsMock.mock.calls.length - 1
]?.[0] as Record<string, unknown>;
expect(lastOpts.themeType).toBe("light");
expect(document.body.dataset.theme).toBe("light");
});
it("wrap toggle switches between wrap and scroll", async () => {
renderCard();
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
const opts1 = fileDiffSetOptionsMock.mock.calls[0]?.[0] as Record<string, unknown>;
expect(opts1.overflow).toBe("wrap");
const renderHeaderMetadata = opts1.renderHeaderMetadata as () => HTMLElement;
const toolbar = renderHeaderMetadata();
const buttons = toolbar.querySelectorAll("button");
buttons[1].click();
const lastOpts = fileDiffSetOptionsMock.mock.calls[
fileDiffSetOptionsMock.mock.calls.length - 1
]?.[0] as Record<string, unknown>;
expect(lastOpts.overflow).toBe("scroll");
});
it("background toggle inverts disableBackground", async () => {
renderCard();
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
const opts1 = fileDiffSetOptionsMock.mock.calls[0]?.[0] as Record<string, unknown>;
expect(opts1.disableBackground).toBe(false);
const renderHeaderMetadata = opts1.renderHeaderMetadata as () => HTMLElement;
const toolbar = renderHeaderMetadata();
const buttons = toolbar.querySelectorAll("button");
buttons[2].click();
const lastOpts = fileDiffSetOptionsMock.mock.calls[
fileDiffSetOptionsMock.mock.calls.length - 1
]?.[0] as Record<string, unknown>;
expect(lastOpts.disableBackground).toBe(true);
});
});
describe("ensureShadowRoot", () => {
beforeEach(() => {
document.body.innerHTML = "";
vi.clearAllMocks();
});
it("attaches shadow root from template and removes template element", async () => {
renderCard();
const host = document.querySelector<HTMLElement>("[data-openclaw-diff-host]")!;
const template = document.createElement("template");
template.setAttribute("shadowrootmode", "open");
template.innerHTML = "<div>shadow content</div>";
host.append(template);
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
expect(host.shadowRoot).toBeDefined();
expect(host.shadowRoot!.querySelector("div")?.textContent).toBe("shadow content");
expect(host.querySelector("template")).toBeNull();
});
it("skips shadow root attachment when no template is present", async () => {
renderCard();
const host = document.querySelector<HTMLElement>("[data-openclaw-diff-host]")!;
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
expect(host.shadowRoot).toBeNull();
expect(fileDiffHydrateMock).toHaveBeenCalled();
});
it("skips shadow root when already attached", async () => {
renderCard();
const host = document.querySelector<HTMLElement>("[data-openclaw-diff-host]")!;
host.attachShadow({ mode: "open" });
host.shadowRoot!.innerHTML = "<span>existing</span>";
const template = document.createElement("template");
template.setAttribute("shadowrootmode", "open");
template.innerHTML = "<div>new content</div>";
host.append(template);
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
expect(host.shadowRoot!.querySelector("span")?.textContent).toBe("existing");
expect(host.querySelector("template")).not.toBeNull();
});
});
describe("getHydrateProps branching", () => {
beforeEach(() => {
document.body.innerHTML = "";
vi.clearAllMocks();
});
it("passes fileDiff directly when payload has fileDiff", async () => {
const fileDiffPayload = JSON.stringify({
prerenderedHTML: "<div>diff</div>",
options: {
theme: { light: "pierre-light", dark: "pierre-dark" },
diffStyle: "unified",
diffIndicators: "bars",
disableLineNumbers: false,
expandUnchanged: false,
themeType: "dark",
backgroundEnabled: true,
overflow: "wrap",
unsafeCSS: "",
},
langs: ["text"],
fileDiff: { name: "patch.diff", lang: "text", hunks: [] },
});
renderCard(fileDiffPayload);
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
const hydrateArg = fileDiffHydrateMock.mock.calls[0]?.[0] as Record<string, unknown>;
expect(hydrateArg.fileDiff).toEqual({ name: "patch.diff", lang: "text", hunks: [] });
expect(hydrateArg.oldFile).toBeUndefined();
expect(hydrateArg.newFile).toBeUndefined();
});
it("passes oldFile and newFile when payload has them without fileDiff", async () => {
renderCard();
const { hydrateViewer } = await import("./viewer-client.js");
await hydrateViewer();
const hydrateArg = fileDiffHydrateMock.mock.calls[0]?.[0] as Record<string, unknown>;
expect(hydrateArg.fileDiff).toBeUndefined();
expect(hydrateArg.oldFile).toEqual({ name: "a.ts", lang: "text", contents: "old" });
expect(hydrateArg.newFile).toEqual({ name: "a.ts", lang: "text", contents: "new" });
});
});

View File

@@ -379,11 +379,6 @@ export async function hasAllGuildPermissionsDiscord(
);
}
/**
* @deprecated Prefer hasAnyGuildPermissionDiscord or hasAllGuildPermissionsDiscord for clarity.
*/
export const hasGuildPermissionDiscord = hasAnyGuildPermissionDiscord;
export async function fetchChannelPermissionsDiscord(
channelId: string,
opts: DiscordReactOpts,

View File

@@ -1,6 +1,7 @@
// Elevenlabs tests cover speech provider plugin behavior.
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
import { buildElevenLabsSpeechProvider, isValidVoiceId } from "./speech-provider.js";
import { isValidElevenLabsVoiceId } from "./shared.js";
import { buildElevenLabsSpeechProvider } from "./speech-provider.js";
vi.mock("openclaw/plugin-sdk/ssrf-runtime", () => ({
fetchWithSsrFGuard: async ({
@@ -119,7 +120,7 @@ describe("elevenlabs speech provider", () => {
{ value: "voice?param=value", expected: false },
] as const;
for (const testCase of cases) {
expect(isValidVoiceId(testCase.value), testCase.value).toBe(testCase.expected);
expect(isValidElevenLabsVoiceId(testCase.value), testCase.value).toBe(testCase.expected);
}
});

View File

@@ -90,8 +90,6 @@ function parseNumberValue(value: string): number | undefined {
return parseStrictFiniteNumber(value);
}
export const isValidVoiceId = isValidElevenLabsVoiceId;
function normalizeVoiceSetting(value: unknown, min: number, max: number): number | undefined {
const number = asFiniteNumber(value);
return number !== undefined && number >= min && number <= max ? number : undefined;

View File

@@ -1,6 +1,6 @@
// File Transfer tests cover errors plugin behavior.
import { describe, expect, it } from "vitest";
import { classifyFsError, err, throwFromNodePayload } from "./errors.js";
import { err, throwFromNodePayload } from "./errors.js";
describe("err", () => {
it("returns an error envelope without canonicalPath when omitted", () => {
@@ -18,28 +18,6 @@ describe("err", () => {
});
});
describe("classifyFsError", () => {
it("maps ENOENT to NOT_FOUND", () => {
expect(classifyFsError({ code: "ENOENT" })).toBe("NOT_FOUND");
});
it("maps EACCES and EPERM to PERMISSION_DENIED", () => {
expect(classifyFsError({ code: "EACCES" })).toBe("PERMISSION_DENIED");
expect(classifyFsError({ code: "EPERM" })).toBe("PERMISSION_DENIED");
});
it("maps EISDIR to IS_DIRECTORY", () => {
expect(classifyFsError({ code: "EISDIR" })).toBe("IS_DIRECTORY");
});
it("falls back to READ_ERROR for unknown / null / non-object input", () => {
expect(classifyFsError({ code: "EUNKNOWN" })).toBe("READ_ERROR");
expect(classifyFsError(null)).toBe("READ_ERROR");
expect(classifyFsError(undefined)).toBe("READ_ERROR");
expect(classifyFsError("nope")).toBe("READ_ERROR");
});
});
describe("throwFromNodePayload", () => {
it("preserves code and message in the thrown Error", () => {
expect(() =>

View File

@@ -42,21 +42,6 @@ export function err(
return { ok: false, code, message, ...(canonicalPath ? { canonicalPath } : {}) };
}
// Translate a node-side fs error to a public error code.
export function classifyFsError(e: unknown): FileTransferErrCode {
const code = (e as { code?: string } | null)?.code;
if (code === "ENOENT") {
return "NOT_FOUND";
}
if (code === "EACCES" || code === "EPERM") {
return "PERMISSION_DENIED";
}
if (code === "EISDIR") {
return "IS_DIRECTORY";
}
return "READ_ERROR";
}
// Convert a node-host error payload to a thrown Error for agent-tool consumption.
// The agent-tool surfaces these as failed tool results uniformly.
export function throwFromNodePayload(operation: string, payload: Record<string, unknown>): never {

View File

@@ -1,7 +1,4 @@
import {
createApproverRestrictedNativeApprovalCapability,
splitChannelApprovalCapability,
} from "openclaw/plugin-sdk/approval-delivery-runtime";
import { createApproverRestrictedNativeApprovalCapability } from "openclaw/plugin-sdk/approval-delivery-runtime";
import { createLazyChannelApprovalNativeRuntimeAdapter } from "openclaw/plugin-sdk/approval-handler-adapter-runtime";
import type { ChannelApprovalNativeRuntimeAdapter } from "openclaw/plugin-sdk/approval-handler-runtime";
import {
@@ -240,7 +237,3 @@ export const googleChatApprovalCapability: ChannelApprovalCapability =
.googleChatApprovalNativeRuntime as unknown as ChannelApprovalNativeRuntimeAdapter,
}),
});
export const googleChatNativeApprovalAdapter = splitChannelApprovalCapability(
googleChatApprovalCapability,
);

View File

@@ -5,7 +5,6 @@ import {
parseIrcPrefix,
sanitizeIrcOutboundText,
sanitizeIrcTarget,
splitIrcText,
} from "./protocol.js";
describe("irc protocol", () => {
@@ -37,13 +36,4 @@ describe("irc protocol", () => {
expect(() => sanitizeIrcTarget(" user")).toThrow(/Invalid IRC target/);
});
it("splits long text on boundaries", () => {
const chunks = splitIrcText("a ".repeat(300), 120);
expect(chunks.length).toBeGreaterThan(2);
expect(
chunks
.map((chunk, index) => ({ index, length: chunk.length }))
.filter((chunk) => chunk.length > 120),
).toStrictEqual([]);
});
});

View File

@@ -141,30 +141,6 @@ export function sanitizeIrcTarget(raw: string): string {
return decoded;
}
export function splitIrcText(text: string, maxChars = 350): string[] {
const cleaned = sanitizeIrcOutboundText(text);
if (!cleaned) {
return [];
}
if (cleaned.length <= maxChars) {
return [cleaned];
}
const chunks: string[] = [];
let remaining = cleaned;
while (remaining.length > maxChars) {
let splitAt = remaining.lastIndexOf(" ", maxChars);
if (splitAt < Math.floor(maxChars * 0.5)) {
splitAt = maxChars;
}
chunks.push(remaining.slice(0, splitAt).trim());
remaining = remaining.slice(splitAt).trimStart();
}
if (remaining) {
chunks.push(remaining);
}
return chunks.filter(Boolean);
}
export function makeIrcMessageId() {
return randomUUID();
}

View File

@@ -15,7 +15,6 @@ afterAll(() => {
});
import {
detectLineMediaKind,
resolveLineOutboundMedia,
validateLineMediaUrl,
} from "./outbound-media.js";
@@ -71,28 +70,6 @@ describe("validateLineMediaUrl", () => {
});
});
describe("detectLineMediaKind", () => {
it("maps image MIME to image", () => {
expect(detectLineMediaKind("image/jpeg")).toBe("image");
});
it("maps uppercase image MIME to image", () => {
expect(detectLineMediaKind("IMAGE/JPEG")).toBe("image");
});
it("maps video MIME to video", () => {
expect(detectLineMediaKind("video/mp4")).toBe("video");
});
it("maps audio MIME to audio", () => {
expect(detectLineMediaKind("audio/mpeg")).toBe("audio");
});
it("falls back unknown MIME to image", () => {
expect(detectLineMediaKind("application/octet-stream")).toBe("image");
});
});
describe("resolveLineOutboundMedia", () => {
beforeEach(() => {
ssrfMocks.resolvePinnedHostnameWithPolicy.mockReset();

View File

@@ -41,20 +41,6 @@ export async function validateLineMediaUrl(url: string): Promise<void> {
});
}
export function detectLineMediaKind(mimeType: string): LineOutboundMediaKind {
const normalized = normalizeLowercaseStringOrEmpty(mimeType);
if (normalized.startsWith("image/")) {
return "image";
}
if (normalized.startsWith("video/")) {
return "video";
}
if (normalized.startsWith("audio/")) {
return "audio";
}
return "image";
}
function isHttpsUrl(url: string): boolean {
try {
return new URL(url).protocol === "https:";

View File

@@ -6,6 +6,7 @@ import path from "node:path";
import type { OpenKeyedStoreOptions } from "openclaw/plugin-sdk/plugin-state-runtime";
import {
createPluginStateKeyedStoreForTests,
createPluginStateSyncKeyedStoreForTests,
resetPluginStateStoreForTests,
} from "openclaw/plugin-sdk/plugin-state-test-runtime";
import { getSessionBindingService, testing } from "openclaw/plugin-sdk/session-binding-runtime";
@@ -197,6 +198,8 @@ describe("matrix thread bindings", () => {
state: {
openKeyedStore: (options: OpenKeyedStoreOptions) =>
createPluginStateKeyedStoreForTests("matrix", options),
openSyncKeyedStore: (options: OpenKeyedStoreOptions) =>
createPluginStateSyncKeyedStoreForTests("matrix", options),
resolveStateDir: () => stateDir,
},
} as PluginRuntime);

View File

@@ -1,7 +1,7 @@
// Mattermost tests cover draft stream plugin behavior.
import { describe, expect, it, vi } from "vitest";
import type { MattermostClient } from "./client.js";
import { buildMattermostToolStatusText, createMattermostDraftStream } from "./draft-stream.js";
import { createMattermostDraftStream } from "./draft-stream.js";
type RequestRecord = {
path: string;
@@ -253,30 +253,3 @@ describe("createMattermostDraftStream", () => {
expect(calls[1]?.path).toBe("/posts/post-1");
});
});
describe("buildMattermostToolStatusText", () => {
it("renders a status with the shared tool label", () => {
expect(buildMattermostToolStatusText({ name: "read" })).toBe("📖 Read");
});
it("honors raw exec detail mode", () => {
expect(
buildMattermostToolStatusText({
name: "exec",
args: { command: "pnpm test -- --watch=false" },
detailMode: "raw",
}),
).toBe("🛠️ run tests, `pnpm test -- --watch=false`");
});
it("can hide raw exec detail from status text", () => {
expect(
buildMattermostToolStatusText({
name: "exec",
args: { command: "pnpm test -- --watch=false" },
detailMode: "raw",
config: { streaming: { preview: { commandText: "status" } } },
}),
).toBe("🛠️ Exec");
});
});

View File

@@ -1,6 +1,5 @@
// Mattermost plugin module implements draft stream behavior.
import { createFinalizableDraftLifecycle } from "openclaw/plugin-sdk/channel-outbound";
import { formatChannelProgressDraftLineForEntry } from "openclaw/plugin-sdk/channel-outbound";
import {
createMattermostPost,
deleteMattermostPost,
@@ -33,27 +32,6 @@ function normalizeMattermostDraftText(text: string, maxChars: number): string {
return `${trimmed.slice(0, Math.max(0, maxChars - 3)).trimEnd()}...`;
}
export function buildMattermostToolStatusText(params: {
name?: string;
phase?: string;
args?: Record<string, unknown>;
detailMode?: "explain" | "raw";
config?: Parameters<typeof formatChannelProgressDraftLineForEntry>[0];
}): string {
return (
formatChannelProgressDraftLineForEntry(
params.config,
{
event: "tool",
name: params.name,
phase: params.phase,
args: params.args,
},
params.detailMode ? { detailMode: params.detailMode } : undefined,
) ?? "Running tool..."
);
}
export function createMattermostDraftStream(params: {
client: MattermostClient;
channelId: string;

View File

@@ -104,7 +104,6 @@ vi.mock("./client.js", async () => {
});
vi.mock("./draft-stream.js", () => ({
buildMattermostToolStatusText: () => "Working",
createMattermostDraftStream: mockState.createMattermostDraftStream,
}));

View File

@@ -17,8 +17,6 @@ import {
resolveMattermostEffectiveReplyToId,
resolveMattermostReplyRootId,
resolveMattermostThreadSessionContext,
shouldFinalizeMattermostPreviewAfterDispatch,
shouldClearMattermostDraftPreview,
shouldSuppressMattermostDefaultToolProgressMessages,
shouldUpdateMattermostDraftToolProgress,
type MattermostMentionGateInput,
@@ -369,35 +367,6 @@ describe("shouldSuppressMattermostDefaultToolProgressMessages", () => {
});
});
describe("shouldClearMattermostDraftPreview", () => {
it("deletes the preview after successful normal final delivery", () => {
expect(
shouldClearMattermostDraftPreview({
finalizedViaPreviewPost: false,
finalReplyDelivered: true,
}),
).toBe(true);
});
it("keeps the preview when final delivery failed", () => {
expect(
shouldClearMattermostDraftPreview({
finalizedViaPreviewPost: false,
finalReplyDelivered: false,
}),
).toBe(false);
});
it("keeps the preview when it already became the final reply", () => {
expect(
shouldClearMattermostDraftPreview({
finalizedViaPreviewPost: true,
finalReplyDelivered: true,
}),
).toBe(false);
});
});
describe("deliverMattermostReplyWithDraftPreview", () => {
it("suppresses reasoning-prefixed finals before preview finalization", async () => {
const draftStream = createDraftStreamMock();
@@ -732,35 +701,6 @@ describe("formatMattermostFinalDeliveryOutcomeLog", () => {
});
});
describe("shouldFinalizeMattermostPreviewAfterDispatch", () => {
it("reuses the preview only for a single eligible final payload", () => {
expect(
shouldFinalizeMattermostPreviewAfterDispatch({
finalCount: 1,
canFinalizeInPlace: true,
}),
).toBe(true);
});
it("falls back to normal sends for multi-payload finals", () => {
expect(
shouldFinalizeMattermostPreviewAfterDispatch({
finalCount: 2,
canFinalizeInPlace: true,
}),
).toBe(false);
});
it("falls back to normal sends when the final cannot be edited into the preview", () => {
expect(
shouldFinalizeMattermostPreviewAfterDispatch({
finalCount: 1,
canFinalizeInPlace: false,
}),
).toBe(false);
});
});
describe("resolveMattermostEffectiveReplyToId", () => {
it("keeps an existing thread root", () => {
expect(

View File

@@ -295,20 +295,6 @@ export function canFinalizeMattermostPreviewInPlace(params: {
);
}
export function shouldClearMattermostDraftPreview(params: {
finalizedViaPreviewPost: boolean;
finalReplyDelivered: boolean;
}): boolean {
return params.finalReplyDelivered && !params.finalizedViaPreviewPost;
}
export function shouldFinalizeMattermostPreviewAfterDispatch(params: {
finalCount: number;
canFinalizeInPlace: boolean;
}): boolean {
return params.finalCount === 1 && params.canFinalizeInPlace;
}
type MattermostDraftPreviewState = {
finalizedViaPreviewPost: boolean;
};

View File

@@ -50,19 +50,22 @@ describe("qa scenario catalog", () => {
expect(
scenarioIds.filter((scenarioId) => requiredScenarioIds.includes(scenarioId)).toSorted(),
).toEqual(requiredScenarioIds);
const nativeExecutionScenarios = pack.scenarios.filter(
(scenario) => scenario.execution.kind !== "flow",
expect(
pack.scenarios
.filter((scenario) => scenario.execution?.kind !== "flow")
.map((scenario) => scenario.id)
.toSorted(),
).toStrictEqual(
[
"channel-message-flows",
"control-ui-chat-flow-playwright",
"gateway-smoke",
"package-openclaw-for-docker",
"plugin-lifecycle-probe",
"qa-otel-smoke",
"ux-matrix-evidence-dashboard",
].toSorted(),
);
expect(nativeExecutionScenarios.length).toBeGreaterThan(0);
for (const scenario of nativeExecutionScenarios) {
const execution = scenario.execution;
if (execution.kind === "flow") {
throw new Error(`expected native execution scenario: ${scenario.id}`);
}
expect(["playwright", "script", "vitest"]).toContain(execution.kind);
expect(fs.existsSync(execution.path), `${scenario.id} execution.path exists`).toBe(true);
expect(execution.flow).toBeUndefined();
}
expect(
pack.scenarios
.filter((scenario) => scenario.execution.kind === "flow")

View File

@@ -52,6 +52,7 @@ import {
callPluginToolsMcp,
findSkill,
handleQaAction,
resolveWorkspaceSkillPath,
writeWorkspaceSkill,
} from "./suite-runtime-agent-tools.js";
import { createTempDirHarness } from "./temp-dir.test-helper.js";
@@ -91,6 +92,25 @@ describe("qa suite runtime agent tools helpers", () => {
expect(skillPath).toBe(path.join(workspaceDir, "skills", "my-skill", "SKILL.md"));
});
it("rejects workspace skill names that escape the skills directory", async () => {
const workspaceDir = await makeTempDir("qa-workspace-");
for (const name of ["", " spaced", "spaced ", ".", "..", "../escape", "..\\escape", "a/b"]) {
expect(() => resolveWorkspaceSkillPath(workspaceDir, name), name).toThrow(
`invalid QA workspace skill name: ${JSON.stringify(name)}`,
);
await expect(
writeWorkspaceSkill({
env: { gateway: { workspaceDir } } as never,
name,
body: "escape",
}),
).rejects.toThrow(`invalid QA workspace skill name: ${JSON.stringify(name)}`);
}
await expect(fs.readdir(path.join(workspaceDir, "skills"))).rejects.toThrow();
});
it("routes generic transport actions through the payload extractor", async () => {
const handleAction = vi.fn(async () => ({
content: [{ type: "text", text: "done" }],

View File

@@ -26,14 +26,36 @@ function findSkill(skills: QaSkillStatusEntry[], name: string) {
return skills.find((skill) => skill.name === name);
}
function resolveWorkspaceSkillPath(workspaceDir: string, name: string) {
const trimmed = name.trim();
if (
!trimmed ||
trimmed !== name ||
trimmed === "." ||
trimmed === ".." ||
trimmed.includes("\0") ||
/[\\/]/u.test(trimmed)
) {
throw new Error(`invalid QA workspace skill name: ${JSON.stringify(name)}`);
}
const skillsDir = path.resolve(workspaceDir, "skills");
const skillDir = path.resolve(skillsDir, trimmed);
const relative = path.relative(skillsDir, skillDir);
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
throw new Error(`invalid QA workspace skill name: ${JSON.stringify(name)}`);
}
return path.join(skillDir, "SKILL.md");
}
async function writeWorkspaceSkill(params: {
env: Pick<QaSuiteRuntimeEnv, "gateway">;
name: string;
body: string;
}) {
const skillDir = path.join(params.env.gateway.workspaceDir, "skills", params.name);
const skillPath = resolveWorkspaceSkillPath(params.env.gateway.workspaceDir, params.name);
const skillDir = path.dirname(skillPath);
await fs.mkdir(skillDir, { recursive: true });
const skillPath = path.join(skillDir, "SKILL.md");
await fs.writeFile(skillPath, `${params.body.trim()}\n`, "utf8");
return skillPath;
}
@@ -113,4 +135,10 @@ async function handleQaAction(params: {
return extractQaToolPayload(result as Parameters<typeof extractQaToolPayload>[0]);
}
export { callPluginToolsMcp, findSkill, handleQaAction, writeWorkspaceSkill };
export {
callPluginToolsMcp,
findSkill,
handleQaAction,
resolveWorkspaceSkillPath,
writeWorkspaceSkill,
};

View File

@@ -183,6 +183,19 @@ describe("containerCheck", () => {
error: "Signal container receive endpoint did not upgrade to WebSocket (HTTP 200)",
});
});
it("rejects container receive endpoints that close before opening", async () => {
wsMockState.behavior = "close";
mockFetch.mockResolvedValue({ ok: true, status: 200 });
const result = await containerCheck("http://localhost:8080", 1000, "+14259798283");
expect(result).toEqual({
ok: false,
status: null,
error: "Signal container receive WebSocket closed before open (1000: done)",
});
});
});
describe("containerRestRequest", () => {

View File

@@ -193,6 +193,14 @@ function containerReceiveCheck(
error: err instanceof Error ? err.message : String(err),
});
});
ws.once("close", (code, reason) => {
const reasonText = reason.length > 0 ? `: ${reason.toString("utf8")}` : "";
settle({
ok: false,
status: null,
error: `Signal container receive WebSocket closed before open (${code}${reasonText})`,
});
});
});
}

View File

@@ -35,7 +35,7 @@ vi.mock("./webhook/tailscale.js", () => ({
getTailscaleDnsName: mocks.getTailscaleDnsName,
}));
import { isNgrokAvailable, startNgrokTunnel, startTailscaleTunnel, startTunnel } from "./tunnel.js";
import { startNgrokTunnel, startTailscaleTunnel, startTunnel } from "./tunnel.js";
function nextProcess(): FakeChildProcess {
const proc = new FakeChildProcess();
@@ -53,25 +53,6 @@ describe("voice-call tunnels", () => {
mocks.getTailscaleDnsName.mockReset();
});
it("checks ngrok availability from the version command exit code", async () => {
const proc = nextProcess();
const result = isNgrokAvailable();
proc.close(0);
await expect(result).resolves.toBe(true);
expect(mocks.spawn).toHaveBeenCalledWith("ngrok", ["version"], {
stdio: "ignore",
});
});
it("treats ngrok spawn failures as unavailable", async () => {
const proc = nextProcess();
const result = isNgrokAvailable();
proc.fail(new Error("spawn ngrok ENOENT"));
await expect(result).resolves.toBe(false);
});
it("starts ngrok and appends the webhook path to the public URL", async () => {
const proc = nextProcess();
const result = startNgrokTunnel({ port: 3334, path: "/voice/webhook" });

View File

@@ -201,25 +201,6 @@ async function runNgrokCommand(args: string[]): Promise<string> {
});
}
/**
* Check if ngrok is installed and available.
*/
export async function isNgrokAvailable(): Promise<boolean> {
return new Promise((resolve) => {
const proc = spawn("ngrok", ["version"], {
stdio: "ignore",
});
proc.on("close", (code) => {
resolve(code === 0);
});
proc.on("error", () => {
resolve(false);
});
});
}
/**
* Start a Tailscale serve/funnel tunnel.
*/

View File

@@ -3,8 +3,6 @@ import { describe, expect, it } from "vitest";
import {
DEFAULT_POLLY_VOICE,
escapeXml,
getOpenAiVoiceNames,
isOpenAiVoice,
mapVoiceToPolly,
} from "./voice-mapping.js";
@@ -23,11 +21,4 @@ describe("voice mapping", () => {
expect(mapVoiceToPolly("unknown")).toBe(DEFAULT_POLLY_VOICE);
expect(mapVoiceToPolly(undefined)).toBe(DEFAULT_POLLY_VOICE);
});
it("detects known openai voices and lists them", () => {
expect(isOpenAiVoice("nova")).toBe(true);
expect(isOpenAiVoice("NOVA")).toBe(true);
expect(isOpenAiVoice("Polly.Joanna")).toBe(false);
expect(getOpenAiVoiceNames()).toEqual(["alloy", "echo", "fable", "onyx", "nova", "shimmer"]);
});
});

View File

@@ -50,17 +50,3 @@ export function mapVoiceToPolly(voice: string | undefined): string {
// Map OpenAI voices to Polly equivalents
return OPENAI_TO_POLLY_MAP[normalizeLowercaseStringOrEmpty(voice)] || DEFAULT_POLLY_VOICE;
}
/**
* Check if a voice name is a known OpenAI voice.
*/
export function isOpenAiVoice(voice: string): boolean {
return normalizeLowercaseStringOrEmpty(voice) in OPENAI_TO_POLLY_MAP;
}
/**
* Get all supported OpenAI voice names.
*/
export function getOpenAiVoiceNames(): string[] {
return Object.keys(OPENAI_TO_POLLY_MAP);
}

View File

@@ -624,6 +624,32 @@ describe("deliverWebReply", () => {
expect(warnContext.mediaUrl).toBe("http://example.com/img.jpg");
});
it("delivers the opening text chunk when the first media fails on a multi-chunk reply", async () => {
const msg = makeMsg();
mockLoadedImageMedia();
mockFirstSendMediaFailure(msg, "boom");
await deliverWebReply({
replyResult: { text: "ALPHALINEBRAVOLINE", mediaUrl: "http://example.com/img.jpg" },
msg,
maxMediaBytes: 1024 * 1024,
textLimit: 9,
replyLogger,
skipLog: true,
});
expect(replyText(msg, 0)).toContain("ALPHALINE");
expect(replyText(msg, 0)).toContain("⚠️ Media failed");
const allReplies = (
msg.platform.reply as unknown as { mock: { calls: unknown[][] } }
).mock.calls
.map((call) => String(call[0]))
.join("\n");
expect(allReplies).toContain("ALPHALINE");
expect(allReplies).toContain("BRAVOLINE");
expect(allReplies).not.toContain("boom");
});
it("still attempts later media after the first media fails", async () => {
vi.clearAllMocks();
const msg = makeMsg();

View File

@@ -340,7 +340,7 @@ export async function deliverWebReply(params: {
return;
}
const warning = "⚠️ Media failed.";
const fallbackTextParts = [remainingText.shift() ?? caption ?? "", warning].filter(Boolean);
const fallbackTextParts = [caption ?? "", warning].filter(Boolean);
const fallbackText = fallbackTextParts.join("\n");
if (!fallbackText) {
return;

View File

@@ -4,7 +4,6 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
isXaiToolEnabled,
resolveFallbackXaiAuth,
resolveXaiToolApiKey,
resolveXaiToolApiKeyWithAuth,
} from "./tool-auth-shared.js";
@@ -81,11 +80,11 @@ describe("xai tool auth helpers", () => {
});
});
it("falls back to runtime, then source config, then env for tool auth", () => {
it("falls back to runtime, then source config, then env for tool auth", async () => {
vi.stubEnv("XAI_API_KEY", "env-key");
expect(
resolveXaiToolApiKey({
await expect(
resolveXaiToolApiKeyWithAuth({
runtimeConfig: {
plugins: {
entries: {
@@ -113,10 +112,10 @@ describe("xai tool auth helpers", () => {
},
},
}),
).toBe("runtime-key");
).resolves.toBe("runtime-key");
expect(
resolveXaiToolApiKey({
await expect(
resolveXaiToolApiKeyWithAuth({
sourceConfig: {
plugins: {
entries: {
@@ -131,9 +130,9 @@ describe("xai tool auth helpers", () => {
},
},
}),
).toBe("source-key");
).resolves.toBe("source-key");
expect(resolveXaiToolApiKey({})).toBe("env-key");
await expect(resolveXaiToolApiKeyWithAuth({})).resolves.toBe("env-key");
});
it("honors explicit disabled flags before auth fallback", () => {
@@ -153,11 +152,11 @@ describe("xai tool auth helpers", () => {
await expect(resolveXaiToolApiKeyWithAuth({ auth })).resolves.toBe("profile-key");
});
it("does not use env fallback when a non-env SecretRef is configured but unavailable", () => {
it("does not use env fallback when a non-env SecretRef is configured but unavailable", async () => {
vi.stubEnv("XAI_API_KEY", "env-key");
expect(
resolveXaiToolApiKey({
await expect(
resolveXaiToolApiKeyWithAuth({
sourceConfig: {
plugins: {
entries: {
@@ -176,7 +175,7 @@ describe("xai tool auth helpers", () => {
},
},
}),
).toBeUndefined();
).resolves.toBeUndefined();
});
it("does not bypass blocked explicit tool config with auth profiles", async () => {
@@ -207,11 +206,11 @@ describe("xai tool auth helpers", () => {
await expect(resolveXaiToolApiKeyWithAuth({ sourceConfig, auth })).resolves.toBeUndefined();
});
it("resolves env SecretRefs from source config when runtime snapshot is unavailable", () => {
it("resolves env SecretRefs from source config when runtime snapshot is unavailable", async () => {
vi.stubEnv("XAI_API_KEY", "xai-secretref-key");
expect(
resolveXaiToolApiKey({
await expect(
resolveXaiToolApiKeyWithAuth({
sourceConfig: {
plugins: {
entries: {
@@ -230,14 +229,14 @@ describe("xai tool auth helpers", () => {
},
},
}),
).toBe("xai-secretref-key");
).resolves.toBe("xai-secretref-key");
});
it("does not read arbitrary env SecretRef ids for xAI tool auth", () => {
it("does not read arbitrary env SecretRef ids for xAI tool auth", async () => {
vi.stubEnv("UNRELATED_SECRET", "should-not-be-read");
expect(
resolveXaiToolApiKey({
await expect(
resolveXaiToolApiKeyWithAuth({
sourceConfig: {
plugins: {
entries: {
@@ -256,14 +255,14 @@ describe("xai tool auth helpers", () => {
},
},
}),
).toBeUndefined();
).resolves.toBeUndefined();
});
it("does not resolve env SecretRefs when provider allowlist excludes XAI_API_KEY", () => {
it("does not resolve env SecretRefs when provider allowlist excludes XAI_API_KEY", async () => {
vi.stubEnv("XAI_API_KEY", "xai-secretref-key");
expect(
resolveXaiToolApiKey({
await expect(
resolveXaiToolApiKeyWithAuth({
sourceConfig: {
secrets: {
providers: {
@@ -290,14 +289,14 @@ describe("xai tool auth helpers", () => {
},
},
}),
).toBeUndefined();
).resolves.toBeUndefined();
});
it("does not resolve env SecretRefs when provider source is not env", () => {
it("does not resolve env SecretRefs when provider source is not env", async () => {
vi.stubEnv("XAI_API_KEY", "xai-secretref-key");
expect(
resolveXaiToolApiKey({
await expect(
resolveXaiToolApiKeyWithAuth({
sourceConfig: {
secrets: {
providers: {
@@ -324,6 +323,6 @@ describe("xai tool auth helpers", () => {
},
},
}),
).toBeUndefined();
).resolves.toBeUndefined();
});
});

View File

@@ -157,20 +157,6 @@ export function resolveFallbackXaiAuth(cfg?: OpenClawConfig): XaiFallbackAuth |
return readLegacyGrokFallbackAuth(cfg);
}
export function resolveXaiToolApiKey(params: {
runtimeConfig?: OpenClawConfig;
sourceConfig?: OpenClawConfig;
}): string | undefined {
const configured = resolveConfiguredXaiToolApiKeyResult(params);
if (configured.status === "available") {
return configured.value;
}
if (configured.status === "blocked") {
return undefined;
}
return readProviderEnvValue([XAI_API_KEY_ENV_VAR]);
}
export async function resolveXaiToolApiKeyWithAuth(params: {
runtimeConfig?: OpenClawConfig;
sourceConfig?: OpenClawConfig;

View File

@@ -714,7 +714,7 @@ export class GatewayClient {
this.suppressedTransientPreHelloCleanCloses += 1;
this.flushPendingErrors(new GatewayClientTransientPreHelloCloseError());
this.scheduleReconnect();
this.opts.onClose?.(code, reasonText, closeInfo);
this.notifyClose(code, reasonText, closeInfo);
return;
}
// Clear persisted device auth state only when device-token auth was active.
@@ -745,16 +745,16 @@ export class GatewayClient {
details: connectErrorDetails,
})
) {
this.opts.onReconnectPaused?.({
this.notifyReconnectPaused({
code,
reason: reasonText,
detailCode: connectErrorDetailCode,
});
this.opts.onClose?.(code, reasonText);
this.notifyClose(code, reasonText);
return;
}
this.scheduleReconnect();
this.opts.onClose?.(code, reasonText);
this.notifyClose(code, reasonText);
});
ws.on("error", (err) => {
this.logDebug(`gateway client error: ${formatGatewayClientErrorForLog(err)}`);
@@ -916,7 +916,7 @@ export class GatewayClient {
: 30_000;
this.lastTick = Date.now();
this.startTickWatch();
this.opts.onHelloOk?.(helloOk);
this.notifyHelloOk(helloOk);
})
.catch((err: unknown) => {
if (err instanceof GatewayClientTransientPreHelloCloseError) {
@@ -1127,6 +1127,38 @@ export class GatewayClient {
}
}
private notifyHelloOk(helloOk: HelloOk): void {
try {
this.opts.onHelloOk?.(helloOk);
} catch (err) {
this.logDebug(
`gateway client hello-ok handler error: ${formatGatewayClientErrorForLog(err)}`,
);
}
}
private notifyReconnectPaused(info: GatewayReconnectPausedInfo): void {
try {
this.opts.onReconnectPaused?.(info);
} catch (err) {
this.logDebug(
`gateway client reconnect paused handler error: ${formatGatewayClientErrorForLog(err)}`,
);
}
}
private notifyClose(code: number, reason: string, info?: GatewayClientCloseInfo): void {
try {
if (info === undefined) {
this.opts.onClose?.(code, reason);
return;
}
this.opts.onClose?.(code, reason, info);
} catch (err) {
this.logDebug(`gateway client close handler error: ${formatGatewayClientErrorForLog(err)}`);
}
}
private resolveConnectScopes(params: {
usingStoredDeviceToken?: boolean;
storedScopes?: string[];

View File

@@ -327,8 +327,10 @@ export class OpenClaw {
});
private readonly replayByRunId = new Map<string, OpenClawEvent[]>();
private connected = false;
private closed = false;
private eventPumpPromise: Promise<void> | null = null;
private eventPumpReady: Promise<void> | null = null;
private closePromise: Promise<void> | null = null;
constructor(options: OpenClawOptions = {}) {
this.transport =
@@ -351,24 +353,45 @@ export class OpenClaw {
}
async connect(): Promise<void> {
this.assertOpen();
if (this.connected) {
await this.startEventPump();
this.assertOpen();
return;
}
if (isConnectableTransport(this.transport)) {
await this.transport.connect();
}
this.assertOpen();
this.connected = true;
await this.startEventPump();
this.assertOpen();
}
async close(): Promise<void> {
await this.transport.close?.();
await this.eventPumpPromise?.catch(() => {});
this.normalizedEvents.close();
this.eventPumpPromise = null;
this.eventPumpReady = null;
this.connected = false;
if (this.closePromise) {
return await this.closePromise;
}
if (this.closed) {
return;
}
this.closed = true;
this.closePromise = (async () => {
try {
await this.transport.close?.();
await this.eventPumpPromise?.catch(() => {});
} finally {
this.normalizedEvents.close();
this.eventPumpPromise = null;
this.eventPumpReady = null;
this.connected = false;
}
})();
try {
await this.closePromise;
} finally {
this.closePromise = null;
}
}
async request<T = unknown>(
@@ -377,6 +400,7 @@ export class OpenClaw {
options?: GatewayRequestOptions,
): Promise<T> {
await this.connect();
this.assertOpen();
return await this.transport.request<T>(method, params, options);
}
@@ -392,13 +416,21 @@ export class OpenClaw {
}
rawEvents(filter?: (event: GatewayEvent) => boolean): AsyncIterable<GatewayEvent> {
this.assertOpen();
return this.transport.events(filter);
}
private assertOpen(): void {
if (this.closed) {
throw new Error("OpenClaw SDK client is closed");
}
}
private async *iterateEvents(
filter?: (event: OpenClawEvent) => boolean,
): AsyncIterable<OpenClawEvent> {
await this.connect();
this.assertOpen();
for await (const event of this.normalizedEvents.stream(filter)) {
yield event;
}
@@ -409,6 +441,7 @@ export class OpenClaw {
filter?: (event: OpenClawEvent) => boolean,
): AsyncIterable<OpenClawEvent> {
await this.connect();
this.assertOpen();
const replayEvents = this.replaySnapshot(runId);
let hasCanonicalAssistantRunEvent = replayEvents.some(isAssistantRunEvent);
let hasTerminalRunEvent = replayEvents.some(isTerminalRunEvent);

View File

@@ -54,6 +54,51 @@ class FakeTransport implements OpenClawTransport {
}
}
class DelayedConnectTransport extends FakeTransport {
connectCalls = 0;
private finishConnectCurrent: (() => void) | null = null;
async connect(): Promise<void> {
this.connectCalls += 1;
await new Promise<void>((resolve) => {
this.finishConnectCurrent = resolve;
});
}
finishConnect(): void {
const finish = this.finishConnectCurrent;
if (!finish) {
throw new Error("expected pending connect");
}
this.finishConnectCurrent = null;
finish();
}
}
class ClosingEventPumpTransport extends FakeTransport {
onFirstEventPoll?: () => void;
override events(): AsyncIterable<GatewayEvent> {
return {
[Symbol.asyncIterator]: (): AsyncIterator<GatewayEvent> => {
let firstPoll = true;
return {
next: async (): Promise<IteratorResult<GatewayEvent>> => {
if (firstPoll) {
firstPoll = false;
this.onFirstEventPoll?.();
await new Promise<void>((resolve) => {
setTimeout(resolve, 0);
});
}
return { done: true, value: undefined as never };
},
};
},
};
}
}
class EventsOnlyTransport implements OpenClawTransport {
constructor(private readonly eventSource: AsyncIterable<GatewayEvent>) {}
@@ -631,6 +676,42 @@ describe("OpenClaw SDK", () => {
]);
});
it("keeps close terminal when it races a pending connect", async () => {
const transport = new DelayedConnectTransport({
"agents.list": { agents: [] },
});
const oc = new OpenClaw({ transport });
const connect = oc.connect();
const close = oc.close();
transport.finishConnect();
await expect(connect).rejects.toThrow("OpenClaw SDK client is closed");
await close;
await expect(oc.agents.list()).rejects.toThrow("OpenClaw SDK client is closed");
await expect(oc.events()[Symbol.asyncIterator]().next()).rejects.toThrow(
"OpenClaw SDK client is closed",
);
expect(() => oc.rawEvents()).toThrow("OpenClaw SDK client is closed");
expect(transport.connectCalls).toBe(1);
expect(transport.calls).toEqual([]);
});
it("does not request after close races event pump startup", async () => {
const transport = new ClosingEventPumpTransport({
"agents.list": { agents: [] },
});
const oc = new OpenClaw({ transport });
let closePromise: Promise<void> | undefined;
transport.onFirstEventPoll = () => {
closePromise = oc.close();
};
await expect(oc.agents.list()).rejects.toThrow("OpenClaw SDK client is closed");
await closePromise;
expect(transport.calls).toEqual([]);
});
it("cancels runs and checks model auth status through current Gateway methods", async () => {
const transport = new FakeTransport({
agent: { status: "accepted", runId: "run_without_session" },

View File

@@ -50,4 +50,49 @@ describe("GatewayClientTransport", () => {
await connectExpectation;
expect(client?.stopAndWait).toHaveBeenCalledTimes(1);
});
it("rejects reconnect attempts after close", async () => {
const transport = new GatewayClientTransport();
await transport.close();
await expect(transport.connect()).rejects.toThrow("gateway transport is closed");
expect(gatewayClientMocks.instances).toHaveLength(0);
});
it("resolves connect when a hello observer throws", async () => {
const onHelloOk = vi.fn(() => {
throw new Error("hello observer failed");
});
const transport = new GatewayClientTransport({ onHelloOk });
const connect = transport.connect();
const client = gatewayClientMocks.instances[0];
expect(() => client?.opts.onHelloOk?.({ sessionId: "session-1" })).toThrow(
"hello observer failed",
);
await expect(connect).resolves.toBeUndefined();
expect(onHelloOk).toHaveBeenCalledWith({ sessionId: "session-1" });
});
it("rejects connect when a connect-error observer throws", async () => {
const onConnectError = vi.fn(() => {
throw new Error("connect observer failed");
});
const transport = new GatewayClientTransport({ onConnectError });
const connect = transport.connect();
const connectExpectation = expect(connect).rejects.toThrow("gateway rejected");
const client = gatewayClientMocks.instances[0];
expect(() => client?.opts.onConnectError?.(new Error("gateway rejected"))).toThrow(
"connect observer failed",
);
await connectExpectation;
expect(onConnectError).toHaveBeenCalledOnce();
expect(client?.stopAndWait).toHaveBeenCalledTimes(1);
});
});

View File

@@ -80,12 +80,16 @@ export class GatewayClientTransport implements ConnectableOpenClawTransport {
private connectPromise: Promise<void> | null = null;
private rejectPendingConnect: ((error: Error) => void) | null = null;
private closePromise: Promise<void> | null = null;
private closed = false;
constructor(options: GatewayClientTransportOptions = {}) {
this.options = options;
}
connect(): Promise<void> {
if (this.closed) {
return Promise.reject(new Error("gateway transport is closed"));
}
if (this.connectPromise) {
return this.connectPromise;
}
@@ -99,21 +103,27 @@ export class GatewayClientTransport implements ConnectableOpenClawTransport {
this.options.onEvent?.(normalized);
},
onHelloOk: (_hello: unknown) => {
this.options.onHelloOk?.(_hello);
this.rejectPendingConnect = null;
resolve();
try {
this.options.onHelloOk?.(_hello);
} finally {
this.rejectPendingConnect = null;
resolve();
}
},
onConnectError: (error: Error) => {
this.options.onConnectError?.(error);
if (this.client === client) {
this.client = null;
try {
this.options.onConnectError?.(error);
} finally {
if (this.client === client) {
this.client = null;
}
if (this.connectPromise) {
this.connectPromise = null;
}
void client.stopAndWait().catch(() => {});
this.rejectPendingConnect = null;
reject(error);
}
if (this.connectPromise) {
this.connectPromise = null;
}
void client.stopAndWait().catch(() => {});
this.rejectPendingConnect = null;
reject(error);
},
onReconnectPaused: this.options.onReconnectPaused,
onClose: this.options.onClose,
@@ -146,6 +156,10 @@ export class GatewayClientTransport implements ConnectableOpenClawTransport {
if (this.closePromise) {
return await this.closePromise;
}
if (this.closed) {
return;
}
this.closed = true;
this.eventsHub.close();
const client = this.client;
this.client = null;

View File

@@ -186,6 +186,13 @@ export function resolveNoteColumns(columns: number | undefined): number {
return columns;
}
export function resolveNoteOutputColumns(message: string, columns: number): number {
const widestLine = message
.split("\n")
.reduce((max, line) => Math.max(max, visibleWidth(line)), 0);
return Math.max(columns, widestLine + 6);
}
function createNoteOutput(columns: number): NodeJS.WriteStream {
if (process.stdout.columns === columns) {
return process.stdout;
@@ -207,8 +214,9 @@ export function note(message: unknown, title?: string) {
return;
}
const columns = resolveNoteColumns(process.stdout.columns);
clackNote(wrapNoteMessage(message, { columns }), stylePromptTitle(title), {
output: createNoteOutput(columns),
const wrappedMessage = wrapNoteMessage(message, { columns });
clackNote(wrappedMessage, stylePromptTitle(title), {
output: createNoteOutput(resolveNoteOutputColumns(wrappedMessage, columns)),
format: (line) => line,
});
}

View File

@@ -1,7 +1,8 @@
import { note as clackNote } from "@clack/prompts";
// Terminal Core tests cover table behavior.
import { afterEach, describe, expect, it, vi } from "vitest";
import { visibleWidth } from "./ansi.js";
import { resolveNoteColumns, wrapNoteMessage } from "./note.js";
import { resolveNoteColumns, resolveNoteOutputColumns, wrapNoteMessage } from "./note.js";
import { renderTable } from "./table.js";
function mockProcessPlatform(platform: NodeJS.Platform): void {
@@ -348,6 +349,33 @@ describe("wrapNoteMessage", () => {
expect(resolveNoteColumns(120)).toBe(120);
});
it("widens note output columns so clack does not re-wrap copy-sensitive lines", () => {
const wrapped = wrapNoteMessage(
[
"- Found 1 session lock file.",
"- ~/.openclaw/agents/main/sessions/9c2acae5-841f-4aea-936b-fdb513b60202.jsonl.lock pid=86519 (alive) age=2m47s stale=no",
].join("\n"),
{ columns: 80 },
);
const writes: string[] = [];
const output = {
columns: resolveNoteOutputColumns(wrapped, 80),
write(chunk: string) {
writes.push(chunk);
return true;
},
} as unknown as NodeJS.WriteStream;
clackNote(wrapped, "Session locks", { output, format: (line) => line });
const rendered = writes.join("");
expect(rendered).toContain(".jsonl.lock");
expect(rendered).not.toContain(".js\n");
expect(rendered).toContain(
"- ~/.openclaw/agents/main/sessions/9c2acae5-841f-4aea-936b-fdb513b60202.jsonl.lock",
);
});
it("coerces nullish and non-string note messages before wrapping", () => {
expect(wrapNoteMessage(undefined, { maxWidth: 20, columns: 80 })).toBe("");
expect(wrapNoteMessage(null, { maxWidth: 20, columns: 80 })).toBe("");

View File

@@ -1,30 +0,0 @@
title: OpenAI-compatible chat tools HTTP API
scenario:
id: openai-compatible-chat-tools
surface: runtime
coverage:
primary:
- gateway.tool-invocation-api
secondary:
- gateway.openai-compatible-apis
- runtime.hosted-tool-use
objective: Verify the OpenAI-compatible chat-completions client and Docker lane preserve strict tool-call API behavior.
successCriteria:
- The Docker lane fails missing or placeholder OpenAI auth before Docker build work starts.
- The generated config preserves strict positive gateway port and timeout values.
- The chat-completions client posts to `/v1/chat/completions` with the expected gateway token and model header.
- Tool-call-only responses are accepted, visible content beside a tool call is rejected, and response bodies remain bounded.
docsRefs:
- docs/gateway/protocol.md
- docs/help/testing.md
- docs/concepts/qa-e2e-automation.md
codeRefs:
- scripts/e2e/lib/openai-chat-tools/client.mjs
- scripts/e2e/lib/openai-chat-tools/write-config.mjs
- scripts/e2e/openai-chat-tools-docker.sh
- test/e2e/qa-lab/runtime/openai-compatible-chat-tools.e2e.test.ts
execution:
kind: vitest
path: test/e2e/qa-lab/runtime/openai-compatible-chat-tools.e2e.test.ts
summary: Vitest coverage for OpenAI-compatible chat-completions tool-call API behavior.

View File

@@ -1,29 +0,0 @@
title: OpenAI web_search minimal reasoning gate
scenario:
id: openai-web-search-minimal
surface: model-provider
coverage:
primary:
- runtime.reasoning-and-cache-controls
secondary:
- web-search.openai-native-web-search
- tools.web-search
objective: Verify the OpenAI web_search minimal-reasoning E2E client distinguishes successful grounded turns from provider schema rejection.
successCriteria:
- Reject mode accepts the expected raw OpenAI schema rejection and the gateway schema wrapper.
- Reject mode fails if the agent run unexpectedly succeeds or fails for unrelated transport reasons.
- Success mode requires an `ok` agent result with the expected marker in visible reply payloads.
- Gateway ports are parsed strictly before connecting.
docsRefs:
- docs/tools/web.md
- docs/help/testing.md
- docs/concepts/qa-e2e-automation.md
codeRefs:
- scripts/e2e/lib/openai-web-search-minimal/client.mjs
- scripts/e2e/openai-web-search-minimal-docker.sh
- test/e2e/qa-lab/runtime/openai-web-search-minimal.e2e.test.ts
execution:
kind: vitest
path: test/e2e/qa-lab/runtime/openai-web-search-minimal.e2e.test.ts
summary: Vitest coverage for OpenAI web_search minimal-reasoning success and rejection validation.

View File

@@ -1,30 +0,0 @@
title: OpenAI native web_search request assertions
scenario:
id: openai-web-search-native-assertions
surface: model-provider
coverage:
primary:
- web-search.openai-native-web-search
- plugins.web-search-and-fetch
secondary:
- web-search.model-and-filter-routing
- tools.web-search
objective: Verify the OpenAI web_search Docker lane assertions require native Responses web_search evidence with bounded diagnostics.
successCriteria:
- A successful request must hit `/v1/responses` with native `web_search` and non-minimal reasoning.
- Large request logs are scanned without missing later success requests.
- Failure diagnostics are bounded and do not dump stale or oversized request bodies.
- Function-shaped `web_search` is rejected as native Responses proof.
docsRefs:
- docs/tools/web.md
- docs/help/testing.md
- docs/concepts/qa-e2e-automation.md
codeRefs:
- scripts/e2e/lib/openai-web-search-minimal/assertions.mjs
- scripts/e2e/lib/openai-web-search-minimal/mock-server.mjs
- test/e2e/qa-lab/runtime/openai-web-search-minimal-assertions.e2e.test.ts
execution:
kind: vitest
path: test/e2e/qa-lab/runtime/openai-web-search-minimal-assertions.e2e.test.ts
summary: Vitest coverage for native OpenAI web_search request-log assertions.

View File

@@ -1,28 +0,0 @@
title: OpenWebUI OpenAI-compatible API probe
scenario:
id: openwebui-openai-compatible
surface: runtime
coverage:
primary:
- gateway.openai-compatible-apis
secondary:
- runtime.hosted-provider-turns
- runtime.provider-specific-model-options
objective: Verify the OpenWebUI E2E probe exercises OpenClaw through OpenWebUI's OpenAI-compatible model and chat APIs.
successCriteria:
- Probe environment limits are parsed strictly and control-plane requests time out quickly.
- Sign-in and model-list error bodies are bounded before diagnostics are emitted.
- Models mode authenticates and finds the OpenClaw model exposed by OpenWebUI.
- Chat mode posts to `/api/chat/completions`, validates the expected nonce, and fails when the reply omits it.
docsRefs:
- docs/help/testing.md
- docs/concepts/qa-e2e-automation.md
codeRefs:
- scripts/e2e/openwebui-probe.mjs
- scripts/e2e/openwebui-docker.sh
- test/e2e/qa-lab/runtime/openwebui-probe.e2e.test.ts
execution:
kind: vitest
path: test/e2e/qa-lab/runtime/openwebui-probe.e2e.test.ts
summary: Vitest coverage for OpenWebUI model and chat-completions probe behavior.

View File

@@ -1,5 +1,6 @@
#!/usr/bin/env node
import fs from "node:fs/promises";
import path from "node:path";
import ts from "typescript";
import {
@@ -32,7 +33,6 @@ const legacyWriterNames = new Set([
const legacyTranscriptWriterNames = new Set([
"appendSessionTranscriptMessage",
"emitSessionTranscriptUpdate",
"rewriteTranscriptEntriesInSessionFile",
]);
const sessionCreateLifecycleWriterNames = new Set([
"applySessionStoreEntryPatch",
@@ -49,6 +49,28 @@ const legacyLifecycleCleanupNames = new Set([
"archiveRemovedSessionTranscripts",
"cleanupArchivedSessionTranscripts",
]);
const sessionStoreRuntimeFileBackedCompatNames = new Set([
"loadSessionStore",
"readSessionEntries",
"readSessionEntry",
"readLatestAssistantTextFromSessionTranscript",
"readSessionStoreReadOnly",
"resolveAndPersistSessionFile",
"resolveSessionFilePath",
"resolveSessionStoreEntry",
"saveSessionStore",
"updateSessionStore",
]);
export const allowedSessionStoreRuntimeFileBackedCompatExports = new Set([
"loadSessionStore",
"readLatestAssistantTextFromSessionTranscript",
"resolveAndPersistSessionFile",
"resolveSessionFilePath",
"resolveSessionStoreEntry",
"saveSessionStore",
"updateSessionStore",
]);
export const migratedSessionAccessorFiles = new Set([
"src/agents/embedded-agent-runner/compaction-successor-transcript.ts",
@@ -253,6 +275,74 @@ function findNamedSessionStoreViolations(content, fileName, legacyNames, legacyK
);
}
export function collectSessionStoreRuntimeFileBackedCompatExports(content, fileName = "source.ts") {
const sourceFile = ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, true);
const exports = new Map();
const rememberExport = (node, exportedName, sourceName = exportedName) => {
if (!sessionStoreRuntimeFileBackedCompatNames.has(sourceName)) {
return;
}
exports.set(exportedName, {
line: toLine(sourceFile, node),
sourceName,
});
};
for (const statement of sourceFile.statements) {
const isExported = statement.modifiers?.some(
(modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword,
);
if (isExported && ts.isVariableStatement(statement)) {
for (const declaration of statement.declarationList.declarations) {
if (ts.isIdentifier(declaration.name)) {
rememberExport(declaration.name, declaration.name.text);
}
}
continue;
}
if (isExported && ts.isFunctionDeclaration(statement) && statement.name) {
rememberExport(statement.name, statement.name.text);
continue;
}
if (
ts.isExportDeclaration(statement) &&
statement.exportClause &&
ts.isNamedExports(statement.exportClause)
) {
for (const specifier of statement.exportClause.elements) {
rememberExport(
specifier,
specifier.name.text,
specifier.propertyName?.text ?? specifier.name.text,
);
}
}
}
return exports;
}
export function findSessionStoreRuntimeFileBackedCompatExportViolations(
content,
fileName = "source.ts",
) {
const exports = collectSessionStoreRuntimeFileBackedCompatExports(content, fileName);
const violations = [];
for (const [exportedName, exported] of exports) {
if (
exportedName !== exported.sourceName ||
!allowedSessionStoreRuntimeFileBackedCompatExports.has(exportedName)
) {
violations.push({
line: exported.line,
reason: `exports unratcheted file-backed SDK session helper "${exported.sourceName}"`,
});
}
}
return violations;
}
export function findSessionAccessorBoundaryViolations(content, fileName = "source.ts") {
const legacyNames = legacyNamesForFile(fileName);
const legacyKind = legacyNames === legacyWholeStoreAccessNames ? "access" : "reader";
@@ -406,6 +496,14 @@ export async function main() {
),
findViolations: findSessionLifecycleCleanupBoundaryViolations,
});
const sessionStoreRuntimePath = path.join(repoRoot, "src/plugin-sdk/session-store-runtime.ts");
const sessionStoreRuntimeCompatViolations =
findSessionStoreRuntimeFileBackedCompatExportViolations(
await fs.readFile(sessionStoreRuntimePath, "utf8"),
sessionStoreRuntimePath,
).map((violation) =>
Object.assign({ path: "src/plugin-sdk/session-store-runtime.ts" }, violation),
);
const violations = [
...readViolations,
...writeViolations,
@@ -413,6 +511,7 @@ export async function main() {
...sessionCreateLifecycleViolations,
...manualCompactTrimViolations,
...lifecycleCleanupViolations,
...sessionStoreRuntimeCompatViolations,
];
if (violations.length === 0) {
@@ -425,7 +524,7 @@ export async function main() {
console.error(`- ${violation.path}:${violation.line}: ${violation.reason}`);
}
console.error(
"Use src/config/sessions/session-accessor.ts helpers for migrated read/write and transcript-writer paths. Expand this ratchet only after a slice migrates more files.",
"Use src/config/sessions/session-accessor.ts helpers for migrated read/write and transcript-writer paths. Expand file-backed SDK compatibility only as an explicit pre-SQLite migration decision.",
);
process.exit(1);
}

View File

@@ -20,7 +20,6 @@ export const KNIP_OPTIONAL_UNUSED_FILE_ALLOWLIST = [
"extensions/memory-core/src/memory-tool-manager-mock.ts",
"ui/src/ui/browser-redact.ts",
"src/agents/subagent-registry.runtime.ts",
"src/auto-reply/inbound.group-require-mention-test-plugins.ts",
"src/auto-reply/reply/get-reply.test-loader.ts",
"src/cli/daemon-cli-compat.ts",
"src/commands/doctor/shared/deprecation-compat.ts",

View File

@@ -22,6 +22,7 @@ FIXTURE_PORT="18080"
TOKEN="browser-cdp-e2e-token"
CONTAINER_NAME="openclaw-browser-cdp-e2e-$$"
DOCKER_COMMAND_TIMEOUT="${OPENCLAW_BROWSER_CDP_SNAPSHOT_DOCKER_COMMAND_TIMEOUT:-900s}"
SNAPSHOT_MAX_BYTES="$(docker_e2e_read_positive_int_env OPENCLAW_BROWSER_CDP_SNAPSHOT_MAX_BYTES 524288)"
cleanup() {
docker_e2e_docker_cmd rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true
@@ -63,6 +64,7 @@ docker_e2e_docker_cmd run -d \
-e OPENCLAW_SKIP_GMAIL_WATCHER=1 \
-e OPENCLAW_SKIP_CRON=1 \
-e OPENCLAW_SKIP_CANVAS_HOST=1 \
-e "OPENCLAW_BROWSER_CDP_SNAPSHOT_MAX_BYTES=$SNAPSHOT_MAX_BYTES" \
-e "OPENCLAW_TEST_STATE_SCRIPT_B64=$OPENCLAW_TEST_STATE_SCRIPT_B64" \
"$IMAGE_NAME" \
bash -lc "set -euo pipefail

View File

@@ -4,12 +4,62 @@ set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$ROOT_DIR/scripts/lib/docker-e2e-image.sh"
IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-bundled-plugin-install-uninstall-e2e" OPENCLAW_BUNDLED_PLUGIN_INSTALL_UNINSTALL_E2E_IMAGE)"
LIST_TIMEOUT_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_LIST_TIMEOUT_MS 30000
)"
LIST_MAX_BUFFER_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_LIST_MAX_BUFFER_BYTES 4194304
)"
RUNTIME_PORT_BASE="$(docker_e2e_read_tcp_port_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_PORT_BASE 19000)"
RUNTIME_OUTPUT_CHARS="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_OUTPUT_CHARS 1048576
)"
RUNTIME_LOG_SCAN_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_LOG_SCAN_BYTES 262144
)"
RUNTIME_GATEWAY_LOG_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_GATEWAY_LOG_BYTES 16777216
)"
RUNTIME_READY_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_READY_MS 900000
)"
RUNTIME_RPC_MS="$(docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_RPC_MS 60000)"
RUNTIME_RPC_READY_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_RPC_READY_MS 210000
)"
RUNTIME_WATCHDOG_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_WATCHDOG_MS 1000
)"
RUNTIME_COMMAND_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_COMMAND_MS 120000
)"
RUNTIME_HTTP_MS="$(docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_HTTP_MS 5000)"
RUNTIME_TEARDOWN_GRACE_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_TEARDOWN_GRACE_MS 10000
)"
RUNTIME_TEARDOWN_KILL_GRACE_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_BUNDLED_PLUGIN_RUNTIME_TEARDOWN_KILL_GRACE_MS 1000
)"
docker_e2e_build_or_reuse "$IMAGE_NAME" bundled-plugin-install-uninstall
OPENCLAW_TEST_STATE_SCRIPT_B64="$(docker_e2e_test_state_shell_b64 bundled-plugin-install-uninstall empty)"
DOCKER_ENV_ARGS=(
-e COREPACK_ENABLE_DOWNLOAD_PROMPT=0
-e "OPENCLAW_BUNDLED_PLUGIN_LIST_TIMEOUT_MS=$LIST_TIMEOUT_MS"
-e "OPENCLAW_BUNDLED_PLUGIN_LIST_MAX_BUFFER_BYTES=$LIST_MAX_BUFFER_BYTES"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_PORT_BASE=$RUNTIME_PORT_BASE"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_OUTPUT_CHARS=$RUNTIME_OUTPUT_CHARS"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_LOG_SCAN_BYTES=$RUNTIME_LOG_SCAN_BYTES"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_GATEWAY_LOG_BYTES=$RUNTIME_GATEWAY_LOG_BYTES"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_READY_MS=$RUNTIME_READY_MS"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_RPC_MS=$RUNTIME_RPC_MS"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_RPC_READY_MS=$RUNTIME_RPC_READY_MS"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_WATCHDOG_MS=$RUNTIME_WATCHDOG_MS"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_COMMAND_MS=$RUNTIME_COMMAND_MS"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_HTTP_MS=$RUNTIME_HTTP_MS"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_TEARDOWN_GRACE_MS=$RUNTIME_TEARDOWN_GRACE_MS"
-e "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_TEARDOWN_KILL_GRACE_MS=$RUNTIME_TEARDOWN_KILL_GRACE_MS"
-e "OPENCLAW_TEST_STATE_SCRIPT_B64=$OPENCLAW_TEST_STATE_SCRIPT_B64"
)
for env_name in \
@@ -18,11 +68,6 @@ for env_name in \
OPENCLAW_BUNDLED_PLUGIN_SWEEP_IDS \
OPENCLAW_BUNDLED_PLUGIN_SWEEP_COMMAND_TIMEOUT \
OPENCLAW_BUNDLED_PLUGIN_RUNTIME_SMOKE \
OPENCLAW_BUNDLED_PLUGIN_RUNTIME_PORT_BASE \
OPENCLAW_BUNDLED_PLUGIN_RUNTIME_OUTPUT_CHARS \
OPENCLAW_BUNDLED_PLUGIN_RUNTIME_READY_MS \
OPENCLAW_BUNDLED_PLUGIN_RUNTIME_RPC_MS \
OPENCLAW_BUNDLED_PLUGIN_RUNTIME_WATCHDOG_MS \
OPENCLAW_BUNDLED_PLUGIN_TTS_LIVE_PROVIDER \
OPENCLAW_PLUGIN_LIFECYCLE_TRACE \
OPENAI_API_KEY; do

View File

@@ -7,6 +7,7 @@ source "$ROOT_DIR/scripts/lib/docker-e2e-image.sh"
IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-codex-media-path-e2e" OPENCLAW_CODEX_MEDIA_PATH_E2E_IMAGE)"
PORT="$(docker_e2e_read_tcp_port_env OPENCLAW_CODEX_MEDIA_PATH_PORT 18790)"
TIMEOUT_SECONDS="$(docker_e2e_read_positive_int_env OPENCLAW_CODEX_MEDIA_PATH_TIMEOUT_SECONDS 180)"
LOG_TAIL_MAX_BYTES="$(docker_e2e_read_positive_int_env OPENCLAW_CODEX_MEDIA_PATH_LOG_TAIL_MAX_BYTES 2097152)"
TOKEN="codex-media-path-e2e-$$"
CODEX_PLUGIN_SPEC="${OPENCLAW_CODEX_MEDIA_PATH_PLUGIN_SPEC:-npm:@openclaw/codex}"
@@ -17,6 +18,7 @@ echo "Running Codex media-path Docker E2E..."
docker_e2e_run_logged_with_harness codex-media-path \
-e COREPACK_ENABLE_DOWNLOAD_PROMPT=0 \
-e "OPENCLAW_CODEX_MEDIA_PATH_PLUGIN_SPEC=$CODEX_PLUGIN_SPEC" \
-e "OPENCLAW_CODEX_MEDIA_PATH_LOG_TAIL_MAX_BYTES=$LOG_TAIL_MAX_BYTES" \
-e "OPENCLAW_CODEX_MEDIA_PATH_TIMEOUT_SECONDS=$TIMEOUT_SECONDS" \
-e "OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1" \
-e "OPENCLAW_GATEWAY_TOKEN=$TOKEN" \

View File

@@ -20,6 +20,24 @@ PROFILE_FILE="${OPENCLAW_CODEX_NPM_PLUGIN_PROFILE_FILE:-${OPENCLAW_TESTBOX_PROFI
CODEX_PLUGIN_SPEC="${OPENCLAW_CODEX_NPM_PLUGIN_SPEC:-}"
CODEX_PLUGIN_MOUNT=()
CODEX_PLUGIN_PACK_DIR=""
ASSERT_MAX_TEXT_FILE_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_TEXT_FILE_BYTES 1048576
)"
ASSERT_MAX_ERROR_TAIL_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_ERROR_TAIL_BYTES 65536
)"
ASSERT_MAX_TRANSCRIPT_FILES="$(
docker_e2e_read_positive_int_env OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_TRANSCRIPT_FILES 64
)"
ASSERT_MAX_TRANSCRIPT_WALK_ENTRIES="$(
docker_e2e_read_positive_int_env OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_TRANSCRIPT_WALK_ENTRIES 4096
)"
ASSERT_MAX_TRANSCRIPT_SCAN_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_TRANSCRIPT_SCAN_BYTES 2097152
)"
AGENT_TURN_TIMEOUT_SECONDS="$(
docker_e2e_read_positive_int_env OPENCLAW_CODEX_NPM_PLUGIN_AGENT_TIMEOUT_SECONDS 420
)"
run_log=""
cleanup() {
@@ -110,6 +128,10 @@ if [ -f "$PROFILE_FILE" ] && [ -r "$PROFILE_FILE" ]; then
PROFILE_MOUNT=(-v "$PROFILE_FILE":/home/appuser/.profile:ro)
PROFILE_STATUS="$PROFILE_FILE"
fi
AGENT_TURN_TIMEOUT_SECONDS="$(
docker_e2e_read_positive_int_env OPENCLAW_CODEX_NPM_PLUGIN_AGENT_TIMEOUT_SECONDS "$AGENT_TURN_TIMEOUT_SECONDS"
)"
COMMAND_TIMEOUT="${OPENCLAW_E2E_COMMAND_TIMEOUT:-$((10#$AGENT_TURN_TIMEOUT_SECONDS + 60))s}"
docker_e2e_package_mount_args "$PACKAGE_TGZ"
run_log="$(docker_e2e_run_log codex-npm-plugin-live)"
@@ -124,6 +146,13 @@ if ! docker_e2e_run_with_harness \
-e OPENCLAW_CODEX_NPM_PLUGIN_FORCE_UNSAFE_INSTALL="${OPENCLAW_CODEX_NPM_PLUGIN_FORCE_UNSAFE_INSTALL:-1}" \
-e OPENCLAW_CODEX_NPM_PLUGIN_MODEL="${OPENCLAW_CODEX_NPM_PLUGIN_MODEL:-codex/gpt-5.4}" \
-e OPENCLAW_CODEX_NPM_PLUGIN_SPEC="$CODEX_PLUGIN_SPEC" \
-e "OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_TEXT_FILE_BYTES=$ASSERT_MAX_TEXT_FILE_BYTES" \
-e "OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_ERROR_TAIL_BYTES=$ASSERT_MAX_ERROR_TAIL_BYTES" \
-e "OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_TRANSCRIPT_FILES=$ASSERT_MAX_TRANSCRIPT_FILES" \
-e "OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_TRANSCRIPT_WALK_ENTRIES=$ASSERT_MAX_TRANSCRIPT_WALK_ENTRIES" \
-e "OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_TRANSCRIPT_SCAN_BYTES=$ASSERT_MAX_TRANSCRIPT_SCAN_BYTES" \
-e "OPENCLAW_CODEX_NPM_PLUGIN_AGENT_TIMEOUT_SECONDS=$AGENT_TURN_TIMEOUT_SECONDS" \
-e "OPENCLAW_E2E_COMMAND_TIMEOUT=$COMMAND_TIMEOUT" \
-e OPENAI_API_KEY \
-e OPENAI_BASE_URL \
-e "OPENCLAW_TEST_STATE_SCRIPT_B64=$OPENCLAW_TEST_STATE_SCRIPT_B64" \
@@ -165,6 +194,7 @@ MODEL_REF="${OPENCLAW_CODEX_NPM_PLUGIN_MODEL:?missing OPENCLAW_CODEX_NPM_PLUGIN_
POST_UNINSTALL_MODEL_REF="codex/${MODEL_REF#*/}"
SESSION_ID="codex-npm-plugin-live"
SUCCESS_MARKER="OPENCLAW-CODEX-NPM-PLUGIN-LIVE-OK"
AGENT_TURN_TIMEOUT_SECONDS="${OPENCLAW_CODEX_NPM_PLUGIN_AGENT_TIMEOUT_SECONDS:-420}"
PLUGIN_INSTALL_FLAGS=(--force)
if [ "${OPENCLAW_CODEX_NPM_PLUGIN_FORCE_UNSAFE_INSTALL:-0}" = "1" ]; then
PLUGIN_INSTALL_FLAGS+=(--dangerously-force-unsafe-install)
@@ -251,7 +281,7 @@ run_agent_turn() {
--model "$MODEL_REF" \
--message "$message" \
--thinking low \
--timeout 420 \
--timeout "$AGENT_TURN_TIMEOUT_SECONDS" \
--json >"$out" 2>"$err" </dev/null; then
status=0
else

View File

@@ -7,6 +7,8 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$ROOT_DIR/scripts/lib/docker-e2e-image.sh"
source "$ROOT_DIR/scripts/lib/docker-e2e-package.sh"
IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-doctor-install-switch-e2e" OPENCLAW_DOCTOR_INSTALL_SWITCH_E2E_IMAGE)"
NPM_INSTALL_TIMEOUT="${OPENCLAW_E2E_NPM_INSTALL_TIMEOUT:-600s}"
COMMAND_TIMEOUT="${OPENCLAW_DOCKER_DOCTOR_SWITCH_COMMAND_TIMEOUT:-900s}"
cleanup() {
docker_e2e_cleanup_package_tgz "${PACKAGE_TGZ:-}"
}
@@ -22,6 +24,8 @@ docker_e2e_build_or_reuse "$IMAGE_NAME" doctor-switch "$ROOT_DIR/scripts/e2e/Doc
echo "Running doctor install switch E2E..."
docker_e2e_run_with_harness \
-e COREPACK_ENABLE_DOWNLOAD_PROMPT=0 \
-e "OPENCLAW_DOCKER_DOCTOR_SWITCH_COMMAND_TIMEOUT=$COMMAND_TIMEOUT" \
-e "OPENCLAW_E2E_NPM_INSTALL_TIMEOUT=$NPM_INSTALL_TIMEOUT" \
-e "OPENCLAW_TEST_STATE_FUNCTION_B64=$OPENCLAW_TEST_STATE_FUNCTION_B64" \
"${DOCKER_E2E_PACKAGE_ARGS[@]}" \
"$IMAGE_NAME" \

View File

@@ -12,6 +12,22 @@ NET_NAME="openclaw-net-e2e-$$"
GW_NAME="openclaw-gateway-e2e-$$"
DOCKER_COMMAND_TIMEOUT="${OPENCLAW_GATEWAY_NETWORK_DOCKER_COMMAND_TIMEOUT:-600s}"
CLIENT_TIMEOUT="${OPENCLAW_GATEWAY_NETWORK_CLIENT_TIMEOUT:-90s}"
CLIENT_LIMIT_ENV_ARGS=()
if [[ -n "${OPENCLAW_GATEWAY_NETWORK_CLIENT_CONNECT_TIMEOUT_MS+x}" ]]; then
CLIENT_CONNECT_TIMEOUT_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_GATEWAY_NETWORK_CLIENT_CONNECT_TIMEOUT_MS 80000
)"
CLIENT_LIMIT_ENV_ARGS+=(
-e "OPENCLAW_GATEWAY_NETWORK_CLIENT_CONNECT_TIMEOUT_MS=$CLIENT_CONNECT_TIMEOUT_MS"
)
elif [[ -n "${OPENCLAW_GATEWAY_NETWORK_CONNECT_READY_TIMEOUT_MS+x}" ]]; then
CONNECT_READY_TIMEOUT_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_GATEWAY_NETWORK_CONNECT_READY_TIMEOUT_MS 80000
)"
CLIENT_LIMIT_ENV_ARGS+=(
-e "OPENCLAW_GATEWAY_NETWORK_CONNECT_READY_TIMEOUT_MS=$CONNECT_READY_TIMEOUT_MS"
)
fi
cleanup() {
docker_e2e_docker_cmd rm -f "$GW_NAME" >/dev/null 2>&1 || true
@@ -49,6 +65,7 @@ echo "Running client container (connect + health)..."
DOCKER_COMMAND_TIMEOUT="$CLIENT_TIMEOUT" run_logged gateway-network-client docker_e2e_docker_run_cmd run --rm \
"${DOCKER_E2E_HARNESS_ARGS[@]}" \
--network "$NET_NAME" \
"${CLIENT_LIMIT_ENV_ARGS[@]}" \
-e "GW_URL=ws://$GW_NAME:$PORT" \
-e "GW_TOKEN=$TOKEN" \
"$IMAGE_NAME" \

View File

@@ -7,6 +7,9 @@ IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-kitchen-sink-plugin-e2e" OPENCL
OPENCLAW_DOCKER_E2E_LOG_PRINT_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_DOCKER_E2E_LOG_PRINT_BYTES 65536
)"
CLAW_HUB_FIXTURE_WAIT_ATTEMPTS="$(
docker_e2e_read_positive_int_env OPENCLAW_CLAWHUB_FIXTURE_WAIT_ATTEMPTS 600
)"
OPENCLAW_TEST_STATE_SCRIPT_B64="$(docker_e2e_test_state_shell_b64 kitchen-sink-plugin empty)"
KITCHEN_SINK_NPM_SPEC="${OPENCLAW_KITCHEN_SINK_NPM_SPEC:-npm:@openclaw/kitchen-sink@latest}"
@@ -48,6 +51,7 @@ docker_e2e_build_or_reuse "$IMAGE_NAME" kitchen-sink-plugin
DOCKER_ENV_ARGS=(
-e COREPACK_ENABLE_DOWNLOAD_PROMPT=0
-e "OPENCLAW_CLAWHUB_FIXTURE_WAIT_ATTEMPTS=$CLAW_HUB_FIXTURE_WAIT_ATTEMPTS"
-e "OPENCLAW_DOCKER_E2E_LOG_PRINT_BYTES=$OPENCLAW_DOCKER_E2E_LOG_PRINT_BYTES"
-e "OPENCLAW_TEST_STATE_SCRIPT_B64=$OPENCLAW_TEST_STATE_SCRIPT_B64"
-e "KITCHEN_SINK_SCENARIOS=$KITCHEN_SINK_SCENARIOS"

View File

@@ -7,7 +7,9 @@ source "$ROOT_DIR/scripts/lib/docker-e2e-image.sh"
IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-kitchen-sink-rpc-e2e" OPENCLAW_KITCHEN_SINK_RPC_E2E_IMAGE)"
MAX_MEMORY_MIB="$(docker_e2e_read_nonnegative_decimal_env OPENCLAW_KITCHEN_SINK_MAX_MEMORY_MIB 2048)"
MAX_CPU_PERCENT="$(docker_e2e_read_nonnegative_decimal_env OPENCLAW_KITCHEN_SINK_MAX_CPU_PERCENT 1200)"
DOCKER_RUN_TIMEOUT="${OPENCLAW_KITCHEN_SINK_RPC_DOCKER_RUN_TIMEOUT:-900s}"
# Keep the outer Docker watchdog above the walker's install, enable, inspect,
# readiness, and first-RPC retry budgets so inner failures stay diagnostic.
DOCKER_RUN_TIMEOUT="${OPENCLAW_KITCHEN_SINK_RPC_DOCKER_RUN_TIMEOUT:-1500s}"
CONTAINER_NAME="openclaw-kitchen-sink-rpc-e2e-$$"
RUN_LOG="$(mktemp "${TMPDIR:-/tmp}/openclaw-kitchen-sink-rpc.XXXXXX")"
STATS_LOG="$(mktemp "${TMPDIR:-/tmp}/openclaw-kitchen-sink-rpc-stats.XXXXXX")"

View File

@@ -892,14 +892,10 @@ export async function fetchJson(url, options = {}) {
let removeExternalAbort = () => {};
const abortPromise = externalSignal
? new Promise((_, reject) => {
const abortError = () =>
externalSignal.reason instanceof Error
? externalSignal.reason
: new Error("fetch aborted");
const onAbort = () => {
const error = abortError();
const error = getExternalAbortReason(externalSignal);
controller.abort(error);
reject(new Error(error.message, { cause: error }));
reject(createExternalAbortError(externalSignal));
};
if (externalSignal.aborted) {
onAbort();
@@ -939,7 +935,7 @@ export async function fetchJson(url, options = {}) {
if (attempt >= attempts || !isRetryableTransientNetworkError(error)) {
throw error;
}
await delay(options.retryDelayMs ?? 250);
await delayWithAbort(options.retryDelayMs ?? 250, externalSignal);
} finally {
removeExternalAbort();
if (timeout) {
@@ -950,6 +946,33 @@ export async function fetchJson(url, options = {}) {
throw toLintErrorObject(lastError ?? new Error(`fetch ${url} failed`), "Non-Error thrown");
}
function getExternalAbortReason(signal) {
return signal?.reason instanceof Error ? signal.reason : new Error("fetch aborted");
}
function createExternalAbortError(signal) {
const reason = getExternalAbortReason(signal);
return new Error(reason.message, { cause: reason });
}
async function delayWithAbort(delayMs, signal) {
if (!signal) {
await delay(delayMs);
return;
}
if (signal.aborted) {
throw createExternalAbortError(signal);
}
try {
await delay(delayMs, undefined, { signal });
} catch (error) {
if (signal.aborted) {
throw createExternalAbortError(signal);
}
throw error;
}
}
export async function readBoundedResponseText(response, byteLimit, timeoutPromise) {
const resolvedByteLimit = byteLimit ?? resolveKitchenSinkRpcConfig().fetchBodyMaxBytes;
const contentLength = response.headers?.get?.("content-length");

View File

@@ -6,6 +6,7 @@ import path from "node:path";
import process from "node:process";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { readBoundedResponseText } from "../bounded-response-text.mjs";
const TOKEN = "bundled-plugin-runtime-smoke-token";
const RUNTIME_PORT_BASE_ENV = "OPENCLAW_BUNDLED_PLUGIN_RUNTIME_PORT_BASE";
@@ -31,6 +32,7 @@ const RPC_READY_TIMEOUT_MS = readPositiveIntEnv(
);
const COMMAND_TIMEOUT_MS = readPositiveIntEnv("OPENCLAW_BUNDLED_PLUGIN_RUNTIME_COMMAND_MS", 120000);
const HTTP_PROBE_TIMEOUT_MS = readPositiveIntEnv("OPENCLAW_BUNDLED_PLUGIN_RUNTIME_HTTP_MS", 5000);
const HTTP_PROBE_BODY_MAX_BYTES = 1024 * 1024;
const GATEWAY_TEARDOWN_GRACE_MS = readPositiveIntEnv(
"OPENCLAW_BUNDLED_PLUGIN_RUNTIME_TEARDOWN_GRACE_MS",
10000,
@@ -693,18 +695,37 @@ export async function waitForReady(params) {
async function fetchHttpProbeStatus(port, pathName, options = {}) {
const { parseJson = false, timeoutMs = HTTP_PROBE_TIMEOUT_MS } = options;
const controller = new AbortController();
const clearProbeTimer = timeoutMs
? setTimeout(() => {
controller.abort();
}, timeoutMs)
const timeoutError = Object.assign(
new Error(`${pathName} probe timed out after ${timeoutMs}ms`),
{
code: "ETIMEDOUT",
},
);
let clearProbeTimer;
const timeoutPromise = timeoutMs
? new Promise((_, reject) => {
clearProbeTimer = setTimeout(() => {
controller.abort(timeoutError);
reject(timeoutError);
}, timeoutMs);
clearProbeTimer.unref?.();
})
: undefined;
try {
const res = await fetch(`http://127.0.0.1:${port}${pathName}`, {
signal: controller.signal,
});
const res = await Promise.race([
fetch(`http://127.0.0.1:${port}${pathName}`, {
signal: controller.signal,
}),
...(timeoutPromise ? [timeoutPromise] : []),
]);
const status = { ok: res.ok, status: res.status, body: undefined, bodyText: undefined };
if (parseJson) {
const text = await res.text();
const text = await readBoundedResponseText(
res,
`${pathName} probe`,
HTTP_PROBE_BODY_MAX_BYTES,
timeoutPromise,
);
status.bodyText = text;
if (text.trim()) {
try {

View File

@@ -37,6 +37,10 @@ const MAX_TRANSCRIPT_SCAN_BYTES = readPositiveIntEnv(
"OPENCLAW_CODEX_NPM_PLUGIN_ASSERT_MAX_TRANSCRIPT_SCAN_BYTES",
2 * 1024 * 1024,
);
const AGENT_TURN_TIMEOUT_SECONDS = readPositiveIntEnv(
"OPENCLAW_CODEX_NPM_PLUGIN_AGENT_TIMEOUT_SECONDS",
420,
);
function readPositiveIntEnv(name, fallback) {
const text = String(process.env[name] ?? fallback).trim();
@@ -100,7 +104,7 @@ function configure() {
mode: "yolo",
approvalPolicy: "never",
sandbox: "danger-full-access",
requestTimeoutMs: 420_000,
requestTimeoutMs: AGENT_TURN_TIMEOUT_SECONDS * 1000,
},
},
},
@@ -117,7 +121,7 @@ function configure() {
},
workspace: path.join(state, "workspace"),
skipBootstrap: true,
timeoutSeconds: 420,
timeoutSeconds: AGENT_TURN_TIMEOUT_SECONDS,
},
};
fs.mkdirSync(path.dirname(cfgPath), { recursive: true });

View File

@@ -53,26 +53,39 @@ function readPositiveInt(raw, fallback, label) {
async function withClickClackFixtureResponse(url, init, consume, options = {}) {
const timeoutMs = options.timeoutMs ?? clickClackHttpTimeoutMs();
const controller = new AbortController();
const timer = setTimeout(() => {
controller.abort();
}, timeoutMs);
const timeoutError = new Error(`${url} timed out after ${timeoutMs}ms`);
let timer;
const timeoutPromise = new Promise((_resolve, reject) => {
timer = setTimeout(() => {
controller.abort(timeoutError);
reject(timeoutError);
}, timeoutMs);
});
try {
const response = await fetch(url, {
...init,
signal: controller.signal,
});
return await consume(response);
const response = await Promise.race([
fetch(url, {
...init,
signal: controller.signal,
}),
timeoutPromise,
]);
return await consume(response, { timeoutPromise });
} finally {
clearTimeout(timer);
}
}
async function readBoundedResponseText(response, label, byteLimit = clickClackHttpBodyMaxBytes()) {
return await readBoundedResponseTextWithLimit(response, label, byteLimit);
async function readBoundedResponseText(
response,
label,
byteLimit = clickClackHttpBodyMaxBytes(),
options = {},
) {
return await readBoundedResponseTextWithLimit(response, label, byteLimit, options.timeoutPromise);
}
async function readBoundedResponseJson(response, label) {
return JSON.parse(await readBoundedResponseText(response, label));
async function readBoundedResponseJson(response, label, options = {}) {
return JSON.parse(await readBoundedResponseText(response, label, undefined, options));
}
function resolveHomePath(value) {
@@ -278,8 +291,10 @@ async function postClickClackInbound() {
headers: { "content-type": "application/json" },
body: JSON.stringify({ body }),
},
async (response) => {
const text = response.ok ? "" : await readBoundedResponseText(response, "ClickClack inbound");
async (response, options) => {
const text = response.ok
? ""
: await readBoundedResponseText(response, "ClickClack inbound", undefined, options);
assert(response.ok, `fixture inbound failed: ${response.status} ${text}`);
},
);
@@ -298,9 +313,9 @@ async function waitClickClackSocket() {
const state = await withClickClackFixtureResponse(
`${baseUrl}/fixture/state`,
{},
async (response) =>
async (response, options) =>
response.ok
? await readBoundedResponseJson(response, "ClickClack fixture state")
? await readBoundedResponseJson(response, "ClickClack fixture state", options)
: undefined,
{
timeoutMs: Math.min(clickClackHttpTimeoutMs(), remainingMs),

View File

@@ -3,6 +3,7 @@
// Probes gateway state for upgrade-survivor E2E scenarios.
import fs from "node:fs";
import path from "node:path";
import { readBoundedResponseText } from "../../../lib/bounded-response.mjs";
const args = process.argv.slice(2);
@@ -104,47 +105,29 @@ function matchesDegradedReadyExpectation(body) {
);
}
async function readBoundedResponseText(response, byteLimit) {
const contentLength = response.headers?.get?.("content-length");
if (contentLength && /^\d+$/u.test(contentLength)) {
const parsedContentLength = Number(contentLength);
if (Number.isSafeInteger(parsedContentLength) && parsedContentLength > byteLimit) {
await response.body?.cancel().catch(() => undefined);
throw new Error(`${url} probe body exceeded ${byteLimit} bytes`);
}
}
const reader = response.body?.getReader();
if (!reader) {
return "";
}
const chunks = [];
let totalBytes = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) {
break;
}
totalBytes += value.byteLength;
if (totalBytes > byteLimit) {
await reader.cancel();
throw new Error(`${url} probe body exceeded ${byteLimit} bytes`);
}
chunks.push(Buffer.from(value));
}
return Buffer.concat(chunks, totalBytes).toString("utf8");
}
async function fetchProbeText() {
const elapsedMs = Date.now() - startedAt;
const remainingMs = Math.max(1, timeoutMs - elapsedMs);
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), Math.min(attemptTimeoutMs, remainingMs));
const attemptDeadlineMs = Math.min(attemptTimeoutMs, remainingMs);
let timer;
const timeoutPromise = new Promise((_resolve, reject) => {
timer = setTimeout(() => {
reject(new Error(`${url} probe attempt timed out after ${attemptDeadlineMs}ms`));
controller.abort();
}, attemptDeadlineMs);
});
try {
const response = await fetch(url, { method: "GET", signal: controller.signal });
const response = await Promise.race([
fetch(url, { method: "GET", signal: controller.signal }),
timeoutPromise,
]);
return {
response,
text: await readBoundedResponseText(response, maxBodyBytes),
text: await readBoundedResponseText(response, `${url} probe`, maxBodyBytes, {
formatTooLargeMessage: (_label, bytes) => `${url} probe body exceeded ${bytes} bytes`,
timeoutPromise,
}),
};
} finally {
clearTimeout(timer);

View File

@@ -12,9 +12,11 @@ IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-live-plugin-tool-e2e" OPENCLAW_
DOCKER_TARGET="${OPENCLAW_LIVE_PLUGIN_TOOL_DOCKER_TARGET:-bare}"
HOST_BUILD="${OPENCLAW_LIVE_PLUGIN_TOOL_HOST_BUILD:-1}"
PACKAGE_TGZ="${OPENCLAW_CURRENT_PACKAGE_TGZ:-}"
PROFILE_FILE="${OPENCLAW_LIVE_PLUGIN_TOOL_PROFILE_FILE:-${OPENCLAW_TESTBOX_PROFILE_FILE:-$HOME/.openclaw-testbox-live.profile}}"
AGENT_TURN_TIMEOUT_SECONDS="$(openclaw_e2e_read_positive_int_env OPENCLAW_LIVE_PLUGIN_TOOL_TIMEOUT_SECONDS 300)"
AGENT_OUTPUT_MAX_BYTES="$(openclaw_e2e_read_positive_int_env OPENCLAW_LIVE_PLUGIN_TOOL_AGENT_OUTPUT_MAX_BYTES 1048576)"
PROFILE_FILE="${OPENCLAW_LIVE_PLUGIN_TOOL_PROFILE_FILE:-${OPENCLAW_TESTBOX_PROFILE_FILE:-$HOME/.openclaw-testbox-live.profile}}"
AGENT_OUTPUT_DUMP_BYTES="$(openclaw_e2e_read_nonnegative_int_env OPENCLAW_LIVE_PLUGIN_TOOL_AGENT_OUTPUT_DUMP_BYTES 16384)"
SESSION_SCAN_MAX_ENTRIES="$(openclaw_e2e_read_positive_int_env OPENCLAW_LIVE_PLUGIN_TOOL_SESSION_SCAN_MAX_ENTRIES 50000)"
run_log=""
cleanup() {
@@ -57,6 +59,8 @@ if [ -f "$PROFILE_FILE" ] && [ -r "$PROFILE_FILE" ]; then
PROFILE_MOUNT=(-v "$PROFILE_FILE":/home/appuser/.profile:ro)
PROFILE_STATUS="$PROFILE_FILE"
fi
AGENT_TURN_TIMEOUT_SECONDS="$(openclaw_e2e_read_positive_int_env OPENCLAW_LIVE_PLUGIN_TOOL_TIMEOUT_SECONDS "$AGENT_TURN_TIMEOUT_SECONDS")"
COMMAND_TIMEOUT="${OPENCLAW_E2E_COMMAND_TIMEOUT:-$((10#$AGENT_TURN_TIMEOUT_SECONDS + 60))s}"
docker_e2e_package_mount_args "$PACKAGE_TGZ"
run_log="$(docker_e2e_run_log live-plugin-tool)"
@@ -69,8 +73,11 @@ if ! docker_e2e_run_with_harness \
-e OPENAI_API_KEY \
-e OPENAI_BASE_URL \
-e OPENCLAW_LIVE_PLUGIN_TOOL_MODEL="${OPENCLAW_LIVE_PLUGIN_TOOL_MODEL:-openai/gpt-5.5}" \
-e "OPENCLAW_LIVE_PLUGIN_TOOL_AGENT_OUTPUT_DUMP_BYTES=$AGENT_OUTPUT_DUMP_BYTES" \
-e "OPENCLAW_LIVE_PLUGIN_TOOL_AGENT_OUTPUT_MAX_BYTES=$AGENT_OUTPUT_MAX_BYTES" \
-e "OPENCLAW_LIVE_PLUGIN_TOOL_SESSION_SCAN_MAX_ENTRIES=$SESSION_SCAN_MAX_ENTRIES" \
-e "OPENCLAW_LIVE_PLUGIN_TOOL_TIMEOUT_SECONDS=$AGENT_TURN_TIMEOUT_SECONDS" \
-e "OPENCLAW_E2E_COMMAND_TIMEOUT=$COMMAND_TIMEOUT" \
-e "OPENCLAW_TEST_STATE_SCRIPT_B64=$OPENCLAW_TEST_STATE_SCRIPT_B64" \
"${DOCKER_E2E_PACKAGE_ARGS[@]}" \
"${PROFILE_MOUNT[@]}" \

View File

@@ -12,6 +12,12 @@ DOCKER_TARGET="${OPENCLAW_NPM_ONBOARD_DOCKER_TARGET:-bare}"
HOST_BUILD="${OPENCLAW_NPM_ONBOARD_HOST_BUILD:-1}"
PACKAGE_TGZ="${OPENCLAW_CURRENT_PACKAGE_TGZ:-}"
CHANNEL="${OPENCLAW_NPM_ONBOARD_CHANNEL:-telegram}"
JSON_ARTIFACT_MAX_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_NPM_ONBOARD_JSON_ARTIFACT_MAX_BYTES 1048576
)"
STATUS_TEXT_MAX_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_NPM_ONBOARD_STATUS_TEXT_MAX_BYTES 1048576
)"
run_log=""
cleanup() {
@@ -56,6 +62,8 @@ echo "Running npm tarball onboard/channel/agent Docker E2E ($CHANNEL)..."
if ! docker_e2e_run_with_harness \
-e COREPACK_ENABLE_DOWNLOAD_PROMPT=0 \
-e OPENCLAW_NPM_ONBOARD_CHANNEL="$CHANNEL" \
-e "OPENCLAW_NPM_ONBOARD_JSON_ARTIFACT_MAX_BYTES=$JSON_ARTIFACT_MAX_BYTES" \
-e "OPENCLAW_NPM_ONBOARD_STATUS_TEXT_MAX_BYTES=$STATUS_TEXT_MAX_BYTES" \
-e "OPENCLAW_TEST_STATE_SCRIPT_B64=$OPENCLAW_TEST_STATE_SCRIPT_B64" \
"${DOCKER_E2E_PACKAGE_ARGS[@]}" \
-i "$IMAGE_NAME" bash -s >"$run_log" 2>&1 <<'EOF'; then

View File

@@ -2,6 +2,7 @@
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$ROOT_DIR/scripts/lib/openclaw-e2e-instance.sh"
source "$ROOT_DIR/scripts/lib/docker-e2e-image.sh"
IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-onboard-e2e" OPENCLAW_ONBOARD_E2E_IMAGE)"
OPENCLAW_TEST_STATE_FUNCTION_B64="$(docker_e2e_test_state_function_b64)"
@@ -9,6 +10,8 @@ MAX_MEMORY_MIB="$(docker_e2e_read_nonnegative_decimal_env OPENCLAW_ONBOARD_MAX_M
MAX_CPU_PERCENT="$(docker_e2e_read_nonnegative_decimal_env OPENCLAW_ONBOARD_MAX_CPU_PERCENT 1200)"
DOCKER_RUN_TIMEOUT="${OPENCLAW_ONBOARD_DOCKER_RUN_TIMEOUT:-1200s}"
COMMAND_TIMEOUT="${OPENCLAW_ONBOARD_COMMAND_TIMEOUT:-${OPENCLAW_E2E_COMMAND_TIMEOUT:-300s}}"
GATEWAY_WAIT_ATTEMPTS="$(openclaw_e2e_read_positive_int_env OPENCLAW_ONBOARD_GATEWAY_WAIT_ATTEMPTS 20)"
GATEWAY_WAIT_INTERVAL_S="$(docker_e2e_read_nonnegative_decimal_env OPENCLAW_ONBOARD_GATEWAY_WAIT_INTERVAL_S 1)"
CONTAINER_NAME="openclaw-onboard-e2e-$$"
RUN_LOG="$(mktemp "${TMPDIR:-/tmp}/openclaw-onboard.XXXXXX")"
STATS_LOG="$(mktemp "${TMPDIR:-/tmp}/openclaw-onboard-stats.XXXXXX")"
@@ -27,6 +30,8 @@ docker_e2e_harness_mount_args
DOCKER_COMMAND_TIMEOUT="$DOCKER_RUN_TIMEOUT" docker_e2e_docker_run_cmd run --name "$CONTAINER_NAME" "${DOCKER_E2E_HARNESS_ARGS[@]}" -t \
-e "OPENCLAW_TEST_STATE_FUNCTION_B64=$OPENCLAW_TEST_STATE_FUNCTION_B64" \
-e "OPENCLAW_E2E_COMMAND_TIMEOUT=$COMMAND_TIMEOUT" \
-e "OPENCLAW_ONBOARD_GATEWAY_WAIT_ATTEMPTS=$GATEWAY_WAIT_ATTEMPTS" \
-e "OPENCLAW_ONBOARD_GATEWAY_WAIT_INTERVAL_S=$GATEWAY_WAIT_INTERVAL_S" \
"$IMAGE_NAME" bash scripts/e2e/lib/onboard/scenario.sh >"$RUN_LOG" 2>&1 &
docker_pid="$!"

View File

@@ -58,6 +58,28 @@ function throwIfFailed(label: string, result: CommandResult, check: boolean | un
throw new Error(`${label} failed with exit code ${result.status}`);
}
const POSIX_GUEST_SCRIPT_CLEANUP_TIMEOUT_MS = 30_000;
function appendCommandResult(phases: PhaseRunner, result: CommandResult): void {
phases.append(result.stdout);
phases.append(result.stderr);
}
function cleanupPosixGuestScript(phases: PhaseRunner, transportArgs: string[]): void {
try {
appendCommandResult(
phases,
run("prlctl", transportArgs, {
check: false,
quiet: true,
timeoutMs: POSIX_GUEST_SCRIPT_CLEANUP_TIMEOUT_MS,
}),
);
} catch {
// Cleanup must not hide the command failure that made the phase useful.
}
}
export async function runWindowsBackgroundPowerShell(
options: WindowsBackgroundPowerShellOptions,
): Promise<void> {
@@ -354,48 +376,36 @@ export class LinuxGuest {
) {}
exec(args: string[], options: GuestExecOptions = {}): string {
const result = run(
"prlctl",
["exec", this.vmName, "/usr/bin/env", "HOME=/root", "OPENCLAW_ALLOW_ROOT=1", ...args],
{
check: false,
input: options.input,
quiet: true,
timeoutMs: this.phases.remainingTimeoutMs(options.timeoutMs),
},
);
const result = run("prlctl", this.transportArgs(args), {
check: false,
input: options.input,
quiet: true,
timeoutMs: this.phases.remainingTimeoutMs(options.timeoutMs),
});
this.phases.append(result.stdout);
this.phases.append(result.stderr);
throwIfFailed("Linux guest command", result, options.check);
return result.stdout.trim();
}
private transportArgs(args: string[]): string[] {
return ["exec", this.vmName, "/usr/bin/env", "HOME=/root", "OPENCLAW_ALLOW_ROOT=1", ...args];
}
bash(script: string): string {
const scriptPath = `/tmp/${guestScriptName("sh")}`;
const write = run(
"prlctl",
[
"exec",
this.vmName,
"/usr/bin/env",
"HOME=/root",
"OPENCLAW_ALLOW_ROOT=1",
"dd",
`of=${scriptPath}`,
"bs=1048576",
],
{
try {
const write = run("prlctl", this.transportArgs(["dd", `of=${scriptPath}`, "bs=1048576"]), {
check: false,
input: `umask 022\n${script}`,
quiet: true,
timeoutMs: this.phases.remainingTimeoutMs(),
},
);
this.phases.append(write.stdout);
this.phases.append(write.stderr);
try {
});
appendCommandResult(this.phases, write);
throwIfFailed("Linux guest script write", write, undefined);
return this.exec(["bash", scriptPath]);
} finally {
this.exec(["rm", "-f", scriptPath], { check: false });
cleanupPosixGuestScript(this.phases, this.transportArgs(["/bin/rm", "-f", scriptPath]));
}
}
}
@@ -420,29 +430,31 @@ export class MacosGuest {
return this.run(args, options).stdout.trim();
}
run(args: string[], options: MacosGuestOptions = {}): CommandResult {
const envArgs = Object.entries({ PATH: this.input.path, ...options.env }).map(
private transportArgs(args: string[], env: Record<string, string> = {}): string[] {
const envArgs = Object.entries({ PATH: this.input.path, ...env }).map(
([key, value]) => `${key}=${value}`,
);
const user = this.input.getUser();
const transportArgs =
this.input.getTransport() === "sudo"
? [
"exec",
this.input.vmName,
"/usr/bin/sudo",
"-H",
"-u",
user,
"/usr/bin/env",
`HOME=${this.input.resolveDesktopHome(user)}`,
`USER=${user}`,
`LOGNAME=${user}`,
...envArgs,
...args,
]
: ["exec", this.input.vmName, "--current-user", "/usr/bin/env", ...envArgs, ...args];
const result = run("prlctl", transportArgs, {
return this.input.getTransport() === "sudo"
? [
"exec",
this.input.vmName,
"/usr/bin/sudo",
"-H",
"-u",
user,
"/usr/bin/env",
`HOME=${this.input.resolveDesktopHome(user)}`,
`USER=${user}`,
`LOGNAME=${user}`,
...envArgs,
...args,
]
: ["exec", this.input.vmName, "--current-user", "/usr/bin/env", ...envArgs, ...args];
}
run(args: string[], options: MacosGuestOptions = {}): CommandResult {
const result = run("prlctl", this.transportArgs(args, options.env), {
check: false,
input: options.input,
quiet: true,
@@ -456,13 +468,13 @@ export class MacosGuest {
sh(script: string, env: Record<string, string> = {}): string {
const scriptPath = `/tmp/${guestScriptName("sh")}`;
this.exec(["/bin/dd", `of=${scriptPath}`, "bs=1048576"], {
input: `umask 022\n${script}`,
});
try {
this.exec(["/bin/dd", `of=${scriptPath}`, "bs=1048576"], {
input: `umask 022\n${script}`,
});
return this.exec(["/bin/bash", scriptPath], { env });
} finally {
this.exec(["/bin/rm", "-f", scriptPath], { check: false });
cleanupPosixGuestScript(this.phases, this.transportArgs(["/bin/rm", "-f", scriptPath]));
}
}
}

View File

@@ -531,6 +531,9 @@ export async function runStreaming(
}, options.timeoutMs);
child.on("error", (error) => {
if (timer) {
clearTimeout(timer);
}
if (killTimer) {
clearTimeout(killTimer);
}

View File

@@ -71,7 +71,12 @@ function posixPrintLogTailFunction(): string {
}`;
}
function posixAssertAgentOkScript(command: string, input: NpmUpdateScriptInput, sessionId: string) {
function posixAssertAgentOkScript(
command: string,
input: NpmUpdateScriptInput,
platform: Extract<Platform, "linux" | "macos">,
sessionId: string,
) {
return `${posixProviderOnlyPluginIsolationScript({
fallbackPluginId: input.auth.modelId.split("/", 1)[0] || "openai",
modelId: input.auth.modelId,
@@ -84,7 +89,7 @@ for attempt in 1 2; do
rm -f "$HOME/.openclaw/agents/main/sessions/$session_id.jsonl"
output_file="$(mktemp)"
set +e
OPENCLAW_ALLOW_ROOT="\${OPENCLAW_ALLOW_ROOT:-}" ${input.auth.apiKeyEnv}=${shellQuote(input.auth.apiKeyValue)} ${command} agent --local --agent main --session-id "$session_id" --message 'Reply with exact ASCII text OK only.' --thinking off --json >"$output_file" 2>&1
OPENCLAW_ALLOW_ROOT="\${OPENCLAW_ALLOW_ROOT:-}" ${input.auth.apiKeyEnv}=${shellQuote(input.auth.apiKeyValue)} ${command} agent --local --agent main --session-id "$session_id" --message 'Reply with exact ASCII text OK only.' --thinking off --timeout ${resolveParallelsModelTimeoutSeconds(platform)} --json >"$output_file" 2>&1
rc=$?
set -e
print_log_tail "$output_file"
@@ -259,7 +264,7 @@ ${posixModelProviderConfigCommands(macosOpenClawCommand, input.auth.modelId, "ma
"$OPENCLAW_BIN" config set agents.defaults.skipBootstrap true --strict-json
"$OPENCLAW_BIN" config set tools.profile minimal
${posixAgentWorkspaceScript("Parallels npm update smoke test assistant.")}
${posixAssertAgentOkScript(macosOpenClawCommand, input, "parallels-npm-update-macos")}`;
${posixAssertAgentOkScript(macosOpenClawCommand, input, "macos", "parallels-npm-update-macos")}`;
}
export function windowsUpdateScript(input: NpmUpdateScriptInput): string {
@@ -403,7 +408,7 @@ ${posixModelProviderConfigCommands("openclaw", input.auth.modelId, "linux")}
openclaw config set agents.defaults.skipBootstrap true --strict-json
openclaw config set tools.profile minimal
${posixAgentWorkspaceScript("Parallels npm update smoke test assistant.")}
${posixAssertAgentOkScript("openclaw", input, "parallels-npm-update-linux")}`;
${posixAssertAgentOkScript("openclaw", input, "linux", "parallels-npm-update-linux")}`;
}
function posixVersionCheck(command: string, expectedNeedle: string): string {

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env -S pnpm tsx
import { spawn } from "node:child_process";
// Npm Update Smoke script supports OpenClaw repository automation.
import { randomUUID } from "node:crypto";
import { spawn } from "node:child_process";
import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
import { copyFile, readFile, rm } from "node:fs/promises";
import path from "node:path";
@@ -1109,23 +1109,32 @@ export class NpmUpdateSmoke {
if (write.status !== 0) {
throw new Error(`failed to write guest script ${scriptPath}: ${write.stderr.trim()}`);
}
const chmod = run("prlctl", ["exec", vm, "/bin/chmod", "755", scriptPath], {
check: false,
quiet: true,
timeoutMs: 30_000,
});
if (chmod.status !== 0) {
throw new Error(`failed to chmod guest script ${scriptPath}: ${chmod.stderr.trim()}`);
try {
const chmod = run("prlctl", ["exec", vm, "/bin/chmod", "755", scriptPath], {
check: false,
quiet: true,
timeoutMs: 30_000,
});
if (chmod.status !== 0) {
throw new Error(`failed to chmod guest script ${scriptPath}: ${chmod.stderr.trim()}`);
}
} catch (error) {
this.removeGuestScript(vm, scriptPath);
throw error;
}
return scriptPath;
}
private removeGuestScript(vm: string, scriptPath: string): void {
run("prlctl", ["exec", vm, "/bin/rm", "-f", scriptPath], {
check: false,
quiet: true,
timeoutMs: 30_000,
});
try {
run("prlctl", ["exec", vm, "/bin/rm", "-f", scriptPath], {
check: false,
quiet: true,
timeoutMs: 30_000,
});
} catch {
// Cleanup must not hide the update failure that made the log useful.
}
}
private async runStreamingToJobLog(
@@ -1181,6 +1190,7 @@ export class NpmUpdateSmoke {
child.on("error", (error) => {
ctx.signal.removeEventListener("abort", abort);
clearTimeout(timer);
if (killTimer) {
clearTimeout(killTimer);
}

View File

@@ -44,6 +44,7 @@ append_positive_number_env() {
append_positive_int_env OPENCLAW_PLUGIN_LIFECYCLE_PHASE_TIMEOUT_MS
append_positive_int_env OPENCLAW_PLUGIN_LIFECYCLE_TIMEOUT_KILL_GRACE_MS
append_positive_int_env OPENCLAW_PLUGIN_LIFECYCLE_METRIC_POLL_MS
append_positive_int_env OPENCLAW_PLUGIN_LIFECYCLE_MAX_RSS_KB
append_positive_int_env OPENCLAW_PLUGIN_LIFECYCLE_MAX_WALL_MS
append_positive_number_env OPENCLAW_PLUGIN_LIFECYCLE_MAX_CPU_CORE_RATIO

View File

@@ -7,6 +7,13 @@ IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-plugins-e2e" OPENCLAW_PLUGINS_E
OPENCLAW_DOCKER_E2E_LOG_PRINT_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_DOCKER_E2E_LOG_PRINT_BYTES 65536
)"
CLAW_HUB_PREFLIGHT_BODY_MAX_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_PLUGINS_E2E_CLAWHUB_PREFLIGHT_BODY_MAX_BYTES 1048576
)"
CLAW_HUB_PREFLIGHT_TIMEOUT_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_PLUGINS_E2E_CLAWHUB_PREFLIGHT_TIMEOUT_MS 30000
)"
PLUGINS_CLI_TIMEOUT="${OPENCLAW_PLUGINS_CLI_TIMEOUT:-180s}"
docker_e2e_build_or_reuse "$IMAGE_NAME" plugins
@@ -14,6 +21,9 @@ OPENCLAW_TEST_STATE_SCRIPT_B64="$(docker_e2e_test_state_shell_b64 plugins empty)
DOCKER_ENV_ARGS=(
-e COREPACK_ENABLE_DOWNLOAD_PROMPT=0
-e "OPENCLAW_DOCKER_E2E_LOG_PRINT_BYTES=$OPENCLAW_DOCKER_E2E_LOG_PRINT_BYTES"
-e "OPENCLAW_PLUGINS_E2E_CLAWHUB_PREFLIGHT_BODY_MAX_BYTES=$CLAW_HUB_PREFLIGHT_BODY_MAX_BYTES"
-e "OPENCLAW_PLUGINS_E2E_CLAWHUB_PREFLIGHT_TIMEOUT_MS=$CLAW_HUB_PREFLIGHT_TIMEOUT_MS"
-e "OPENCLAW_PLUGINS_CLI_TIMEOUT=$PLUGINS_CLI_TIMEOUT"
-e "OPENCLAW_TEST_STATE_SCRIPT_B64=$OPENCLAW_TEST_STATE_SCRIPT_B64"
)
for env_name in \
@@ -32,7 +42,8 @@ if [[ "${OPENCLAW_PLUGINS_E2E_LIVE_CLAWHUB:-0}" = "1" ]]; then
CLAWHUB_URL \
OPENCLAW_CLAWHUB_TOKEN \
CLAWHUB_TOKEN \
CLAWHUB_AUTH_TOKEN; do
CLAWHUB_AUTH_TOKEN \
OPENCLAW_PLUGINS_E2E_LIVE_NPM_REGISTRY; do
env_value="${!env_name:-}"
if [[ -n "$env_value" && "$env_value" != "undefined" && "$env_value" != "null" ]]; then
DOCKER_ENV_ARGS+=(-e "$env_name")

View File

@@ -9,6 +9,12 @@ source "$ROOT_DIR/scripts/lib/docker-e2e-package.sh"
IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-release-user-journey-e2e" OPENCLAW_RELEASE_USER_JOURNEY_E2E_IMAGE)"
SKIP_BUILD="${OPENCLAW_RELEASE_USER_JOURNEY_E2E_SKIP_BUILD:-0}"
HTTP_TIMEOUT_MS="$(
docker_e2e_read_positive_int_env OPENCLAW_RELEASE_USER_JOURNEY_HTTP_TIMEOUT_MS 5000
)"
HTTP_BODY_MAX_BYTES="$(
docker_e2e_read_positive_int_env OPENCLAW_RELEASE_USER_JOURNEY_HTTP_BODY_MAX_BYTES 1048576
)"
run_log=""
cleanup() {
docker_e2e_cleanup_package_tgz "${PACKAGE_TGZ:-}"
@@ -28,6 +34,8 @@ run_log="$(docker_e2e_run_log release-user-journey)"
echo "Running release user journey Docker E2E..."
if ! docker_e2e_run_with_harness \
-e COREPACK_ENABLE_DOWNLOAD_PROMPT=0 \
-e "OPENCLAW_RELEASE_USER_JOURNEY_HTTP_TIMEOUT_MS=$HTTP_TIMEOUT_MS" \
-e "OPENCLAW_RELEASE_USER_JOURNEY_HTTP_BODY_MAX_BYTES=$HTTP_BODY_MAX_BYTES" \
-e "OPENCLAW_TEST_STATE_SCRIPT_B64=$OPENCLAW_TEST_STATE_SCRIPT_B64" \
"${DOCKER_E2E_PACKAGE_ARGS[@]}" \
-i "$IMAGE_NAME" bash scripts/e2e/lib/release-user-journey/scenario.sh >"$run_log" 2>&1; then

View File

@@ -18,11 +18,33 @@ UPDATE_RESTART_MODE="${OPENCLAW_UPGRADE_SURVIVOR_UPDATE_RESTART_MODE:-manual}"
COMMAND_TIMEOUT="${OPENCLAW_UPGRADE_SURVIVOR_COMMAND_TIMEOUT:-900s}"
START_BUDGET_SECONDS="$(openclaw_e2e_read_positive_int_env OPENCLAW_UPGRADE_SURVIVOR_START_BUDGET_SECONDS 90)"
STATUS_BUDGET_SECONDS="$(openclaw_e2e_read_positive_int_env OPENCLAW_UPGRADE_SURVIVOR_STATUS_BUDGET_SECONDS 30)"
PROBE_TIMEOUT_MS="$(openclaw_e2e_read_nonnegative_int_env OPENCLAW_UPGRADE_SURVIVOR_PROBE_TIMEOUT_MS 60000)"
PROBE_ATTEMPT_TIMEOUT_MS="$(
openclaw_e2e_read_positive_int_env OPENCLAW_UPGRADE_SURVIVOR_PROBE_ATTEMPT_TIMEOUT_MS 5000
)"
PROBE_MAX_BODY_BYTES="$(
openclaw_e2e_read_positive_int_env OPENCLAW_UPGRADE_SURVIVOR_PROBE_MAX_BODY_BYTES 1048576
)"
LANE_ARTIFACT_SUFFIX="${OPENCLAW_DOCKER_ALL_LANE_NAME:-default}"
LANE_ARTIFACT_SUFFIX="${LANE_ARTIFACT_SUFFIX//[^A-Za-z0-9_.-]/_}"
ARTIFACT_DIR="${OPENCLAW_UPGRADE_SURVIVOR_ARTIFACT_DIR:-$ROOT_DIR/.artifacts/upgrade-survivor/$LANE_ARTIFACT_SUFFIX}"
ROOT_MANAGED_VPS="${OPENCLAW_UPGRADE_SURVIVOR_ROOT_MANAGED_VPS:-0}"
DOCKER_RUN_USER_ARGS=()
PROBE_ENV_ARGS=(
-e OPENCLAW_UPGRADE_SURVIVOR_PROBE_TIMEOUT_MS="$PROBE_TIMEOUT_MS"
-e OPENCLAW_UPGRADE_SURVIVOR_PROBE_ATTEMPT_TIMEOUT_MS="$PROBE_ATTEMPT_TIMEOUT_MS"
-e OPENCLAW_UPGRADE_SURVIVOR_PROBE_MAX_BODY_BYTES="$PROBE_MAX_BODY_BYTES"
)
if [ -n "${OPENCLAW_UPGRADE_SURVIVOR_READYZ_ALLOW_FAILING:-}" ]; then
PROBE_ENV_ARGS+=(
-e OPENCLAW_UPGRADE_SURVIVOR_READYZ_ALLOW_FAILING="$OPENCLAW_UPGRADE_SURVIVOR_READYZ_ALLOW_FAILING"
)
fi
if [ -n "${OPENCLAW_UPGRADE_SURVIVOR_READYZ_ALLOW_DEGRADED:-}" ]; then
PROBE_ENV_ARGS+=(
-e OPENCLAW_UPGRADE_SURVIVOR_READYZ_ALLOW_DEGRADED="$OPENCLAW_UPGRADE_SURVIVOR_READYZ_ALLOW_DEGRADED"
)
fi
cleanup_outer() {
docker_e2e_cleanup_package_tgz "${PACKAGE_TGZ:-}"
}
@@ -112,6 +134,7 @@ if [ "${OPENCLAW_UPGRADE_SURVIVOR_PUBLISHED_BASELINE:-0}" = "1" ]; then
-e OPENCLAW_UPGRADE_SURVIVOR_SUMMARY_JSON=/tmp/openclaw-upgrade-survivor-artifacts/summary.json \
-e OPENCLAW_UPGRADE_SURVIVOR_START_BUDGET_SECONDS="$START_BUDGET_SECONDS" \
-e OPENCLAW_UPGRADE_SURVIVOR_STATUS_BUDGET_SECONDS="$STATUS_BUDGET_SECONDS" \
"${PROBE_ENV_ARGS[@]}" \
-v "$ARTIFACT_DIR:/tmp/openclaw-upgrade-survivor-artifacts" \
"${DOCKER_E2E_PACKAGE_ARGS[@]}" \
"${DOCKER_RUN_USER_ARGS[@]}" \
@@ -139,6 +162,7 @@ docker_e2e_run_with_harness \
-e OPENCLAW_UPGRADE_SURVIVOR_COMMAND_TIMEOUT="$COMMAND_TIMEOUT" \
-e OPENCLAW_UPGRADE_SURVIVOR_START_BUDGET_SECONDS="$START_BUDGET_SECONDS" \
-e OPENCLAW_UPGRADE_SURVIVOR_STATUS_BUDGET_SECONDS="$STATUS_BUDGET_SECONDS" \
"${PROBE_ENV_ARGS[@]}" \
-v "$ARTIFACT_DIR:/tmp/openclaw-upgrade-survivor-artifacts" \
"${DOCKER_E2E_PACKAGE_ARGS[@]}" \
"${DOCKER_RUN_USER_ARGS[@]}" \
@@ -371,11 +395,20 @@ node scripts/e2e/lib/upgrade-survivor/probe-gateway.mjs \
--path /healthz \
--expect live \
--out /tmp/openclaw-upgrade-survivor-healthz.json
node scripts/e2e/lib/upgrade-survivor/probe-gateway.mjs \
--base-url "http://127.0.0.1:$PORT" \
--path /readyz \
--expect ready \
--out /tmp/openclaw-upgrade-survivor-readyz.json
readyz_probe_args=(
--base-url "http://127.0.0.1:$PORT"
--path /readyz
--expect ready
)
if [ -n "${OPENCLAW_UPGRADE_SURVIVOR_READYZ_ALLOW_FAILING:-}" ]; then
readyz_probe_args+=(--allow-failing "$OPENCLAW_UPGRADE_SURVIVOR_READYZ_ALLOW_FAILING")
fi
if [ "${OPENCLAW_UPGRADE_SURVIVOR_READYZ_ALLOW_DEGRADED:-}" = "1" ]; then
readyz_probe_args+=(--allow-degraded-ready)
fi
readyz_probe_args+=(--out /tmp/openclaw-upgrade-survivor-readyz.json)
node scripts/e2e/lib/upgrade-survivor/probe-gateway.mjs "${readyz_probe_args[@]}"
echo "Checking gateway RPC status..."
status_start="$(node -e "process.stdout.write(String(Date.now()))")"

View File

@@ -11,6 +11,7 @@ export const dependencyGraphGuardMarker = "<!-- openclaw:dependency-graph-guard
export const dependencyChangedLabel = "dependencies-changed";
export const allowDependenciesCommand = "/allow-dependencies-change";
export const GITHUB_ERROR_BODY_MAX_BYTES = 64 * 1024;
export const GITHUB_RESPONSE_BODY_MAX_BYTES = 4 * 1024 * 1024;
export const GITHUB_API_REQUEST_TIMEOUT_MS = 30_000;
const maxListedFiles = 25;
@@ -489,12 +490,33 @@ function githubErrorBodyTooLarge(maxBytes) {
return new Error(`GitHub error response body exceeded ${maxBytes} bytes`);
}
export async function readBoundedGitHubErrorText(response, maxBytes = GITHUB_ERROR_BODY_MAX_BYTES) {
function githubResponseBodyTooLarge(maxBytes) {
return new Error(`GitHub response body exceeded ${maxBytes} bytes`);
}
export async function readBoundedGitHubErrorText(
response,
maxBytes = GITHUB_ERROR_BODY_MAX_BYTES,
options = {},
) {
return await readBoundedResponseText(response, "GitHub error", maxBytes, {
createTooLargeError: () => githubErrorBodyTooLarge(maxBytes),
...options,
});
}
export async function readBoundedGitHubJson(
response,
maxBytes = GITHUB_RESPONSE_BODY_MAX_BYTES,
options = {},
) {
const text = await readBoundedResponseText(response, "GitHub", maxBytes, {
createTooLargeError: () => githubResponseBodyTooLarge(maxBytes),
...options,
});
return JSON.parse(text);
}
function timeoutError(path, method, timeoutMs) {
return new Error(`GitHub API ${method} ${path} exceeded timeout ${timeoutMs}ms`);
}
@@ -513,6 +535,7 @@ function combineAbortSignals(signals) {
export function githubApi(token, options = {}) {
const fetchImpl = options.fetchImpl ?? fetch;
const timeoutMs = options.timeoutMs ?? GITHUB_API_REQUEST_TIMEOUT_MS;
const responseMaxBodyBytes = options.responseMaxBodyBytes ?? GITHUB_RESPONSE_BODY_MAX_BYTES;
const baseHeaders = {
accept: "application/vnd.github+json",
authorization: `Bearer ${token}`,
@@ -542,7 +565,10 @@ export function githubApi(token, options = {}) {
if (!response.ok) {
let errorText;
try {
errorText = await readBoundedGitHubErrorText(response);
errorText = await readBoundedGitHubErrorText(response, GITHUB_ERROR_BODY_MAX_BYTES, {
signal: timeoutController.signal,
timeoutPromise,
});
} catch (bodyError) {
errorText = bodyError instanceof Error ? bodyError.message : String(bodyError);
}
@@ -550,7 +576,10 @@ export function githubApi(token, options = {}) {
error.status = response.status;
throw error;
}
return response.json();
return await readBoundedGitHubJson(response, responseMaxBodyBytes, {
signal: timeoutController.signal,
timeoutPromise,
});
})();
operationPromise.catch(() => {});
try {

View File

@@ -10,6 +10,7 @@ export const securitySensitiveGuardMarker = "<!-- openclaw:security-sensitive-gu
export const securitySensitiveChangedLabel = "security-sensitive-changed";
export const allowSecuritySensitiveCommand = "/allow-security-sensitive-change";
export const GITHUB_ERROR_BODY_MAX_BYTES = 64 * 1024;
export const GITHUB_RESPONSE_BODY_MAX_BYTES = 4 * 1024 * 1024;
export const GITHUB_API_REQUEST_TIMEOUT_MS = 30_000;
const securityTeamSlug = process.env.OPENCLAW_SECURITY_TEAM_SLUG ?? "openclaw-secops";
@@ -349,12 +350,33 @@ function githubErrorBodyTooLarge(maxBytes) {
return new Error(`GitHub error response body exceeded ${maxBytes} bytes`);
}
export async function readBoundedGitHubErrorText(response, maxBytes = GITHUB_ERROR_BODY_MAX_BYTES) {
function githubResponseBodyTooLarge(maxBytes) {
return new Error(`GitHub response body exceeded ${maxBytes} bytes`);
}
export async function readBoundedGitHubErrorText(
response,
maxBytes = GITHUB_ERROR_BODY_MAX_BYTES,
options = {},
) {
return await readBoundedResponseText(response, "GitHub error", maxBytes, {
createTooLargeError: () => githubErrorBodyTooLarge(maxBytes),
...options,
});
}
export async function readBoundedGitHubJson(
response,
maxBytes = GITHUB_RESPONSE_BODY_MAX_BYTES,
options = {},
) {
const text = await readBoundedResponseText(response, "GitHub", maxBytes, {
createTooLargeError: () => githubResponseBodyTooLarge(maxBytes),
...options,
});
return JSON.parse(text);
}
function timeoutError(path, method, timeoutMs) {
return new Error(`GitHub API ${method} ${path} exceeded timeout ${timeoutMs}ms`);
}
@@ -373,6 +395,7 @@ function combineAbortSignals(signals) {
export function githubApi(token, options = {}) {
const fetchImpl = options.fetchImpl ?? fetch;
const timeoutMs = options.timeoutMs ?? GITHUB_API_REQUEST_TIMEOUT_MS;
const responseMaxBodyBytes = options.responseMaxBodyBytes ?? GITHUB_RESPONSE_BODY_MAX_BYTES;
const baseHeaders = {
accept: "application/vnd.github+json",
authorization: `Bearer ${token}`,
@@ -402,7 +425,10 @@ export function githubApi(token, options = {}) {
if (!response.ok) {
let errorText;
try {
errorText = await readBoundedGitHubErrorText(response);
errorText = await readBoundedGitHubErrorText(response, GITHUB_ERROR_BODY_MAX_BYTES, {
signal: timeoutController.signal,
timeoutPromise,
});
} catch (bodyError) {
errorText = bodyError instanceof Error ? bodyError.message : String(bodyError);
}
@@ -410,7 +436,10 @@ export function githubApi(token, options = {}) {
error.status = response.status;
throw error;
}
return response.json();
return await readBoundedGitHubJson(response, responseMaxBodyBytes, {
signal: timeoutController.signal,
timeoutPromise,
});
})();
operationPromise.catch(() => {});
try {

View File

@@ -255,7 +255,7 @@ function kitchenSinkRpcLane() {
{
resources: ["npm"],
stateScenario: "empty",
timeoutMs: 15 * 60 * 1000,
timeoutMs: 25 * 60 * 1000,
weight: 3,
},
);
@@ -521,17 +521,13 @@ export const mainLanes = [
lane("commitments-safety", "OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:commitments-safety", {
stateScenario: "empty",
}),
liveLane(
"npm-telegram-live",
"OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:npm-telegram-live",
{
e2eImageKind: "bare",
provider: "openai",
resources: ["live:telegram", "npm", "service"],
timeoutMs: 30 * 60 * 1000,
weight: 3,
},
),
liveLane("npm-telegram-live", "OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:npm-telegram-live", {
e2eImageKind: "bare",
provider: "openai",
resources: ["live:telegram", "npm", "service"],
timeoutMs: 30 * 60 * 1000,
weight: 3,
}),
lane("qr", "pnpm test:docker:qr"),
];

View File

@@ -36,17 +36,24 @@ export function evaluateToleratedPartialKovaReport(report) {
return { ok: false, reason: `blocking count was ${JSON.stringify(gate.blockingCount)}` };
}
const baselineRegressionCount = numericCount(
report?.baseline?.comparison?.regressionCount ?? report?.gate?.baseline?.regressionCount,
);
if (baselineRegressionCount === undefined) {
return { ok: false, reason: "missing baseline regression count" };
}
if (baselineRegressionCount !== 0) {
return {
ok: false,
reason: `baseline regression count was ${JSON.stringify(baselineRegressionCount)}`,
};
const reportBaseline = report?.baseline;
const gateBaseline = report?.gate?.baseline;
if (
(reportBaseline !== null && reportBaseline !== undefined) ||
(gateBaseline !== null && gateBaseline !== undefined)
) {
const baselineRegressionCount = numericCount(
reportBaseline?.comparison?.regressionCount ?? gateBaseline?.regressionCount,
);
if (baselineRegressionCount === undefined) {
return { ok: false, reason: "missing baseline regression count" };
}
if (baselineRegressionCount !== 0) {
return {
ok: false,
reason: `baseline regression count was ${JSON.stringify(baselineRegressionCount)}`,
};
}
}
const statuses = report?.summary?.statuses;

View File

@@ -2,6 +2,7 @@
import { execFileSync } from "node:child_process";
import { resolve } from "node:path";
import { validateExternalCodePluginPackageJson } from "../../packages/plugin-package-contract/src/index.ts";
import { readBoundedResponseText } from "./bounded-response.ts";
import {
collectExtensionPackageJsonCandidates,
collectChangedPathsFromGitRange,
@@ -86,6 +87,8 @@ type ClawHubPublishablePluginPackageFilters = {
};
const CLAWHUB_DEFAULT_REGISTRY = "https://clawhub.ai";
const CLAWHUB_REQUEST_TIMEOUT_MS = 30_000;
const CLAWHUB_RESPONSE_BODY_MAX_BYTES = 64 * 1024;
const OPENCLAW_PLUGIN_CLAWHUB_REPOSITORY = "openclaw/openclaw";
const OPENCLAW_PLUGIN_CLAWHUB_WORKFLOW_FILENAME = "plugin-clawhub-release.yml";
const SAFE_EXTENSION_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
@@ -114,6 +117,58 @@ function getRegistryBaseUrl(explicit?: string) {
);
}
type ClawHubRequestOptions = {
fetchImpl?: typeof fetch;
requestTimeoutMs?: number;
};
async function fetchClawHubRequest(
url: URL,
options: ClawHubRequestOptions = {},
): Promise<{
clearTimeout: () => void;
response: Response;
signal: AbortSignal;
timeoutPromise: Promise<never>;
}> {
const timeoutMs = options.requestTimeoutMs ?? CLAWHUB_REQUEST_TIMEOUT_MS;
const controller = new AbortController();
const timeoutError = Object.assign(
new Error(`ClawHub request timed out after ${timeoutMs}ms: ${url.href}`),
{ code: "ETIMEDOUT" },
);
let timeout: ReturnType<typeof setTimeout> | undefined;
const timeoutPromise = new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => {
controller.abort(timeoutError);
reject(timeoutError);
}, timeoutMs);
timeout.unref?.();
});
try {
const response = await Promise.race([
(options.fetchImpl ?? fetch)(url, {
method: "GET",
headers: {
Accept: "application/json",
},
signal: controller.signal,
}),
timeoutPromise,
]);
return {
clearTimeout: () => clearTimeout(timeout),
response,
signal: controller.signal,
timeoutPromise,
};
} catch (error) {
clearTimeout(timeout);
throw error;
}
}
function formatClawHubPackageArtifactName(
plugin: Pick<PublishablePluginPackage, "packageName" | "version">,
) {
@@ -346,30 +401,33 @@ async function isPluginVersionPublishedOnClawHub(
options: {
fetchImpl?: typeof fetch;
registryBaseUrl?: string;
requestTimeoutMs?: number;
} = {},
): Promise<boolean> {
const fetchImpl = options.fetchImpl ?? fetch;
const url = new URL(
`/api/v1/packages/${encodeURIComponent(packageName)}/versions/${encodeURIComponent(version)}`,
getRegistryBaseUrl(options.registryBaseUrl),
);
const response = await fetchImpl(url, {
method: "GET",
headers: {
Accept: "application/json",
},
const request = await fetchClawHubRequest(url, {
fetchImpl: options.fetchImpl,
requestTimeoutMs: options.requestTimeoutMs,
});
const { response } = request;
if (response.status === 404) {
return false;
}
if (response.ok) {
return true;
}
try {
if (response.status === 404) {
return false;
}
if (response.ok) {
return true;
}
throw new Error(
`Failed to query ClawHub for ${packageName}@${version}: ${response.status} ${response.statusText}`,
);
throw new Error(
`Failed to query ClawHub for ${packageName}@${version}: ${response.status} ${response.statusText}`,
);
} finally {
request.clearTimeout();
}
}
async function doesClawHubPackageExist(
@@ -377,30 +435,33 @@ async function doesClawHubPackageExist(
options: {
fetchImpl?: typeof fetch;
registryBaseUrl?: string;
requestTimeoutMs?: number;
} = {},
): Promise<boolean> {
const fetchImpl = options.fetchImpl ?? fetch;
const url = new URL(
`/api/v1/packages/${encodeURIComponent(packageName)}`,
getRegistryBaseUrl(options.registryBaseUrl),
);
const response = await fetchImpl(url, {
method: "GET",
headers: {
Accept: "application/json",
},
const request = await fetchClawHubRequest(url, {
fetchImpl: options.fetchImpl,
requestTimeoutMs: options.requestTimeoutMs,
});
const { response } = request;
if (response.status === 404) {
return false;
}
if (!response.ok) {
throw new Error(
`Failed to query ClawHub package ${packageName}: ${response.status} ${response.statusText}`,
);
}
try {
if (response.status === 404) {
return false;
}
if (!response.ok) {
throw new Error(
`Failed to query ClawHub package ${packageName}: ${response.status} ${response.statusText}`,
);
}
return true;
return true;
} finally {
request.clearTimeout();
}
}
async function hasClawHubTrustedPublisher(
@@ -408,36 +469,48 @@ async function hasClawHubTrustedPublisher(
options: {
fetchImpl?: typeof fetch;
registryBaseUrl?: string;
requestTimeoutMs?: number;
} = {},
): Promise<boolean> {
const fetchImpl = options.fetchImpl ?? fetch;
const url = new URL(
`/api/v1/packages/${encodeURIComponent(packageName)}/trusted-publisher`,
getRegistryBaseUrl(options.registryBaseUrl),
);
const response = await fetchImpl(url, {
method: "GET",
headers: {
Accept: "application/json",
},
const request = await fetchClawHubRequest(url, {
fetchImpl: options.fetchImpl,
requestTimeoutMs: options.requestTimeoutMs,
});
const { response } = request;
if (!response.ok) {
throw new Error(
`Failed to query ClawHub trusted publisher for ${packageName}: ${response.status} ${response.statusText}`,
);
}
let trustedPublisherDetail: ClawHubTrustedPublisherDetail;
try {
trustedPublisherDetail = (await response.json()) as ClawHubTrustedPublisherDetail;
} catch (error) {
throw new Error(`Failed to parse ClawHub trusted publisher ${packageName} response.`, {
cause: error,
});
}
if (!response.ok) {
throw new Error(
`Failed to query ClawHub trusted publisher for ${packageName}: ${response.status} ${response.statusText}`,
);
}
return isOpenClawPluginTrustedPublisher(trustedPublisherDetail.trustedPublisher);
let trustedPublisherDetail: ClawHubTrustedPublisherDetail;
const text = await readBoundedResponseText(
response,
`ClawHub trusted publisher ${packageName}`,
CLAWHUB_RESPONSE_BODY_MAX_BYTES,
{
signal: request.signal,
timeoutPromise: request.timeoutPromise,
},
);
try {
trustedPublisherDetail = JSON.parse(text) as ClawHubTrustedPublisherDetail;
} catch (error) {
throw new Error(`Failed to parse ClawHub trusted publisher ${packageName} response.`, {
cause: error,
});
}
return isOpenClawPluginTrustedPublisher(trustedPublisherDetail.trustedPublisher);
} finally {
request.clearTimeout();
}
}
function isOpenClawPluginTrustedPublisher(value: unknown): boolean {
@@ -470,6 +543,7 @@ export async function collectPluginClawHubReleasePlan(params?: {
gitRange?: GitRangeSelection;
registryBaseUrl?: string;
fetchImpl?: typeof fetch;
requestTimeoutMs?: number;
}): Promise<PluginReleasePlan> {
const rootDir = params?.rootDir;
const selection = params?.selection ?? [];
@@ -506,17 +580,20 @@ export async function collectPluginClawHubReleasePlan(params?: {
const packageExists = await doesClawHubPackageExist(plugin.packageName, {
registryBaseUrl: params?.registryBaseUrl,
fetchImpl: params?.fetchImpl,
requestTimeoutMs: params?.requestTimeoutMs,
});
const hasTrustedPublisher = packageExists
? await hasClawHubTrustedPublisher(plugin.packageName, {
registryBaseUrl: params?.registryBaseUrl,
fetchImpl: params?.fetchImpl,
requestTimeoutMs: params?.requestTimeoutMs,
})
: false;
const alreadyPublished = packageExists
? await isPluginVersionPublishedOnClawHub(plugin.packageName, plugin.version, {
registryBaseUrl: params?.registryBaseUrl,
fetchImpl: params?.fetchImpl,
requestTimeoutMs: params?.requestTimeoutMs,
})
: false;

View File

@@ -42,6 +42,11 @@ export type NpmViewFields = {
tarball?: string;
};
type FetchWithRetryResult = {
response: Response;
signal: AbortSignal;
};
type WorkflowRunSummary = {
id: string;
label: string;
@@ -262,16 +267,17 @@ async function fetchWithRetry(
url: string,
options: RequestInit,
attempts: number,
): Promise<Response> {
): Promise<FetchWithRetryResult> {
let lastError: unknown;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
const signal = AbortSignal.timeout(CLAWHUB_REQUEST_TIMEOUT_MS);
const response = await fetch(url, {
...options,
signal: AbortSignal.timeout(CLAWHUB_REQUEST_TIMEOUT_MS),
signal,
});
if (response.status !== 429 && response.status < 500) {
return response;
return { response, signal };
}
lastError = new Error(`HTTP ${response.status}`);
} catch (error) {
@@ -288,23 +294,28 @@ async function fetchWithRetry(
}
async function fetchJsonWithRetry(url: string): Promise<unknown> {
const response = await fetchWithRetry(url, { headers: { accept: "application/json" } }, 5);
const { response, signal } = await fetchWithRetry(
url,
{ headers: { accept: "application/json" } },
5,
);
if (!response.ok) {
throw new Error(`${url} returned HTTP ${response.status}.`);
}
return await readBoundedJsonResponse(response, url);
return await readBoundedJsonResponse(response, url, undefined, { signal });
}
export async function readBoundedJsonResponse(
response: Response,
label: string,
maxBytes = CLAWHUB_RESPONSE_BODY_MAX_BYTES,
options: { signal?: AbortSignal } = {},
): Promise<unknown> {
return parseJson(await readBoundedResponseText(response, label, maxBytes), label);
return parseJson(await readBoundedResponseText(response, label, maxBytes, options), label);
}
async function fetchStatusWithRetry(url: string, method: "GET" | "HEAD"): Promise<number> {
const response = await fetchWithRetry(url, { method, redirect: "manual" }, 5);
const { response } = await fetchWithRetry(url, { method, redirect: "manual" }, 5);
return response.status;
}

Some files were not shown because too many files have changed in this diff Show More