Skip to content

fix(zcode): launch hooks via hidden wscript VBS — no console flash, bounded wait - #596

Merged
jeff-r2026 merged 9 commits into
Tencent:mainfrom
hc-tec:feat/zcode-hidden-hooks
Sep 18, 2026
Merged

jeff-r2026 merged 9 commits into
Tencent:mainfrom
hc-tec:feat/zcode-hidden-hooks

Conversation

@hc-tec

@hc-tec hc-tec commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Summary

  • ZCode hook entries on Windows now launch through wscript.exe (GUI subsystem) running a small
    teamai-hook-dispatch.vbs written next to config.json — the VBS executes the dispatch
    hidden (window style 0) and fire-and-forget
  • Eliminates the visible console-window flash on every hook run when ZCode desktop runs on Windows
  • Session start stays instant: the launcher does not wait for the dispatch, so network pulls
    never block the session

Context: why cmd / bash entries are problematic for ZCode

ZCode desktop (Windows) spawns process-type hook entries directly:

  • cmd /c "..." allocates a visible console window when spawned by the desktop app — every
    hook run flashed a black box over the desktop (reported by our team during dogfooding)
  • bare bash is not safe either: CreateProcess resolves it to System32's WSL launcher before
    any PATH directory, and the WSL side has a different $HOME (no teamai state) and often no
    Node ≥ 20 — the hook then no-ops or dies silently
  • wscript.exe is a GUI-subsystem binary that is always present, so it is the only reliable
    launcher on Windows

Design

  • Entries keep the strict-schema shape (type / command / args / timeoutMs); the payload
    travels verbatim as a single argument (args[1]), so managed-entry detection and the
    managed-hooks manifest keep the one-command-representation invariant introduced for team hooks
  • The VBS launcher is written next to config.json (one per scope) and is idempotent —
    re-injection does not duplicate it
  • Per-event network-scale timeouts (SessionStart 180s, others 30–60s) still bound the runner
  • POSIX (macOS/Linux) entries keep bash -lc; there is no console-window concept there
  • Adapter note: this does not touch the migrating installed-hooks mechanism — that remains a
    follow-up once its storage/format is documented

Validation

  • npx vitest run src/__tests__/zcode.test.ts — 11/11 passed (shape assertions updated:
    wscript.exe + payload arg, VBS launcher existence, matcher rules)
  • affected suites green; npm run typecheck, npm run build pass
  • live dogfood on Windows: entries written by hooks inject, session-start auto-pull completed
    through the hidden launcher (teamai status last-pull refreshed), zero hook.run.failed
    entries for the wscript entries, second sync byte-identical (idempotent)

Boundary

  • no new runtime dependency (wscript.exe ships with Windows; POSIX keeps bash)
  • rules are not synced (ZCode has no user-level rules dir convention)
  • adapting to the migrating installed-hooks mechanism remains a follow-up once its
    storage/format is documented

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature causing existing behavior to change)
  • Documentation only
  • Refactor / internal cleanup

Test Plan

  • npx tsc --noEmit passes
  • npx vitest run passes
  • Added/updated tests for the change

Related Issues

…on-blocking

Windows console children (cmd / bash) allocate a visible console window
when spawned by the desktop app, so every hook run flashed a black box;
and inline network pulls could exceed short timeouts. ZCode entries now
launch through wscript.exe (GUI subsystem, present in System32) running a
teamai-hook-dispatch.vbs written next to config.json: the VBS runs the
dispatch hidden (window style 0) and does not wait for it, so session
start stays instant. The payload travels verbatim as a single argument,
preserving the manifest command invariant. POSIX entries keep bash -lc.

@jeff-r2026 jeff-r2026 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for chasing the console flash — wscript.exe is the right primitive for a GUI-subsystem launcher on Windows. CI is green and the branch is mergeable, but as it stands I don't think this can land: the implementation is narrower than the PR description in one place and wider in another.

The two blockers

  1. The process.platform === 'win32' branch is gone, so wscript.exe is written on every platform. The description says POSIX keeps bash -lc; the code doesn't. Existing macOS/Linux entries get replaced on the next reconcile.
  2. The VBS launcher drops STDIN and makes all four events fire-and-forget, which breaks the payload contract hook-dispatch relies on and removes the effect of the per-event timeoutMs table. Details inline.

Smaller things worth folding in

  • removeAll never deletes teamai-hook-dispatch.vbs, so uninstall leaves it behind.
  • The zcodeEntryCommand doc comment ("Both variants (posix bash -lc / win32 cmd /c)") no longer describes the code.
  • Behavior change isn't reflected in the docs. docs/usage-guide.md still says hook entries use "bash -lc <dispatch> as an argv vector", and the zh-CN guide has the matching sentence. Per the repo rules both need updating in the same PR.

Suggested validation after the rework

On Windows: SessionStart auto-pull, plus a PostToolUse event with a Skill / TodoWrite matcher to confirm tool_name actually arrives. On macOS or Linux: confirm the written entry is still bash -lc and that reconcile stays idempotent across the platform change.

Comment thread src/hooks.ts Outdated
// managed-entry detection and the manifest keep one command representation.
const entry: ZcodeHookEntry = {
type: 'process',
command: 'wscript.exe',

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This writes wscript.exe unconditionally — the process.platform === 'win32' branch that used to pick cmd vs bash is gone, which contradicts the "POSIX (macOS/Linux) entries keep bash -lc" line in the PR description.

On macOS/Linux the next reconcile will swap the existing bash -lc entries for this one: the payload still lives in args[1], so isManaged recognizes them as managed and rewrites them. ZCode then tries to spawn a launcher that doesn't exist on those platforms and every hook stops firing.

The Ubuntu and macOS CI jobs don't catch this because the test was changed to assert wscript.exe on all platforms too. Could you restore the platform branch and keep wscript.exe scoped to win32?

Comment thread src/hooks.ts Outdated
[
"' TeamAI hook dispatcher - hidden, fire-and-forget (no console window).",
'Set sh = CreateObject("WScript.Shell")',
'If WScript.Arguments.Count > 0 Then sh.Run "cmd /c " & WScript.Arguments(0), 0, False',

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three concerns with this line.

STDIN is dropped. WScript.Shell.Run starts a fresh process with no inherited stdin pipe, so whatever ZCode writes to wscript.exe never reaches teamai. hook-dispatch reads its payload from STDIN JSON (cwd, tool_name, tool_input, prompt). SessionStart may still look fine because the pull handler can fall back to the child's cwd — which matches what the dogfood run observed — but PostToolUse track / todowrite-hint no-op without tool_name, UserPromptSubmit loses prompt, and any Stop-time hint can't reach the host. Spooling the payload to a temp file and redirecting it into the command would keep the contract intact.

Wait=False is applied too broadly. All four events become fire-and-forget, not just SessionStart. The pull handler is already registered with background: true in the dispatcher, so it doesn't need this; meanwhile the ZCODE_TIMEOUT_MS table above (SessionStart 180s, Stop 60s, …) no longer bounds anything, since the launcher returns immediately regardless.

The payload isn't escaped. "cmd /c " & WScript.Arguments(0) concatenates the command straight into cmd. Built-in dispatch commands survive it, but team hooks are arbitrary strings — the test suite itself uses sh /tmp/audit.sh — and one &, >, or embedded quote gets re-split by cmd. Arguments(0) needs cmd-level quoting.

Comment thread src/hooks.ts Outdated
const expanded = expandHome(settingsPath);
await ensureDir(path.dirname(expanded));
const vbsPath = path.join(path.dirname(expanded), 'teamai-hook-dispatch.vbs');
if (!opts.removeAll) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two minor points on the write itself:

  • The !opts.removeAll guard means uninstall skips the write, but nothing ever deletes teamai-hook-dispatch.vbs — removeAll should remove it so teardown leaves no stray file next to config.json.
  • This rewrites the VBS on every reconcile, even when the content is identical. The rest of this function is careful to only write on change (the changed flag); worth matching that so a no-op sync doesn't touch the file's mtime.

Comment thread src/__tests__/zcode.test.ts Outdated
// wscript.exe is a GUI-subsystem binary — hook runs never flash a
// console window, and the hidden VBS launcher keeps the session
// start non-blocking even while the dispatch pulls over the network.
expect(hook.command).toBe('wscript.exe');

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the platform conditional removed here, the macOS and Ubuntu CI jobs no longer assert anything about the POSIX entry shape — which is why the regression above passes CI. If the win32 branch comes back in toZcodeEntry, this assertion should branch with it.

The PR's Validation section also mentions a "VBS launcher existence" assertion, but I don't see one in the diff; a check that teamai-hook-dispatch.vbs is written next to config.json (and removed by removeAll) would be a good addition.

…t launcher

Aligns the test assertions and zcodeEntryCommand extraction with the
wscript launcher argv (vbsPath, mode, payload). The explicitly configured
timeout (team hooks.yaml / builtin.overrides) now wins over the
per-event table, and the table is the per-event default otherwise.
@jeff-r2026

Copy link
Copy Markdown
Collaborator

Review — hook launch mechanism looks broken as written

Thanks for tackling the console-flash — the direction (GUI-subsystem launcher, spooled stdin, per-event timeouts) is sound. But reading the PR head, I think the argv ↔ VBS contract is mismatched and ZCode hooks won't actually dispatch. Details below, ordered by severity.

🔴 P0 — VBS launcher and argv contract are mismatched; dispatch never runs correctly

toZcodeEntry writes argv [vbsPath, 'wait', def.command] (src/hooks.ts:335):

wscript.exe <vbsPath> wait "teamai hook-dispatch SessionStart --tool zcode"

But the VBS reads WScript.Arguments(0) and hardcodes the teamai hook-dispatch prefix (src/hooks.ts:581):

sh.Run "cmd /d /s /c ""teamai hook-dispatch " & WScript.Arguments(0) & " < """ & spool & """ >nul 2>&1""", 0, True

Under wscript.exe, the script path is not part of WScript.Arguments — the collection starts at the first user arg:

VBS expression actual value
WScript.Arguments(0) "wait" ← treated as the event
WScript.Arguments(1) def.command (the full payload) ← never read

So every hook run actually executes:

cmd /d /s /c "teamai hook-dispatch wait < <spool> >nul 2>&1"

i.e. event = wait (not a real event) and --tool zcode is dropped entirely. The real event (SessionStart/Stop/…) and --tool live in Arguments(1), which is ignored. Session-start auto-pull and any team-hook dispatch won't fire.

Note that simply bumping the index to Arguments(1) doesn't fix it either — you'd get a doubled prefix: teamai hook-dispatch teamai hook-dispatch SessionStart --tool zcode. The root cause is two incompatible argv contracts glued together: the layout is [vbsPath, mode, payload], but the VBS implements [vbsPath, event]. Looks like the commit-1→commit-2 change only migrated half of it.

Fix (pick one, keep both sides aligned):

  • VBS runs the full payload: ... /c """ & WScript.Arguments(1) & " < ..." and drop the hardcoded prefix; or
  • Change argv to [vbsPath, event] and let the VBS build the prefix — but then --tool needs another path in.

Also, the 'wait' mode arg is never consumed by the VBS — sh.Run(..., 0, True) hardcodes the wait flag as True. It does nothing except occupy Arguments(0) and push the event out of reach.

🟠 P1 — VBS file leaks on uninstall (removeAll)

src/hooks.ts:584-591:

const existingVbs = await readFileSafe(vbsPath);
if (existingVbs !== vbsScript) {   // deletion is gated on "content differs"
  if (opts.removeAll) {
    await rmSync(vbsPath, { force: true });
  } else {
    await writeFile(vbsPath, vbsScript);
  }
}

When uninstalling and the on-disk VBS already equals the latest script (existingVbs === vbsScript), the whole if is skipped and the VBS is never removed — an orphan file is left behind. Deletion shouldn't be gated on content equality; the removeAll branch should delete unconditionally. Suggest hoisting removeAll out to its own top-level check.

🟠 P1/P2 — wscript.exe reading WScript.StdIn is unreliable (directly threatens the stdin contract)

hook-dispatch depends on the stdin JSON {hook_event_name, cwd, session_id} (consumed by resolveHookCwd/deriveSessionId). The spool-file approach is reasonable, but:

  • Accessing WScript.StdIn under wscript.exe (GUI subsystem) is notoriously unreliable — reliable stdin access is a cscript.exe (console host) feature; under wscript it commonly throws or reads empty.
  • The read is wrapped in On Error Resume Next (src/hooks.ts:578-580), so a throw here is silently swallowed → empty spool → hook-dispatch gets no cwd/session_id → degraded or no-op.

Worth confirming on a real Windows/ZCode box that the spool file actually has content (not just that last-pull refreshed).

🟡 P2 — cmd string-concat metacharacter hazard

src/hooks.ts:581 concatenates the payload straight into cmd /c "...". The comment claims it's "cmd-level quoted so team-declared commands survive cmd's operator parsing", but there's only the one outer quote layer — a matcher (from team hooks.yaml) containing & | > < would still break parsing. The comment's stated protection doesn't match the implementation.

🟡 P2 — test blind spot (how P0 stayed green)

The updated zcode.test.ts only asserts argv shape (args[1] === 'wait', args[2] contains the dispatch command) and that the VBS exists. It never asserts that the VBS script content is semantically aligned with the argv it's given, so 11/11 passed can't prove the mechanism works — P0 slipped through exactly this gap. Suggest asserting that the VBS references the payload-bearing argument and that the executed event/tool match the def (or snapshot the rendered VBS).

🔵 P3 — rmSync style inconsistency

src/hooks.ts:2 pulls in the sync rmSync and then await rmSync(...) inside an async fn (rmSync returns undefined synchronously; the await is a no-op and misleading). The rest of this file goes through the async wrappers in ./utils/fs.js. Suggest rm from fs/promises or a utils wrapper for consistency.

⚠️ On the "Validation" section

The body says "session-start auto-pull completed … teamai status last-pull refreshed". Per P0, the executed command is teamai hook-dispatch wait, which can't drive normal dispatch — so a refreshed last-pull most likely came from another path (a co-installed Claude/other-tool hook, a manual pull, or stale state). This is the classic "hooks inject prints success even when nothing effective happened" trap (shape-correct ≠ actually ran). Recommend re-running this validation with Process Monitor / added logging to capture the actual command line executed on Windows before trusting it.


Suggested path: fix P0 (align the argv/VBS parameter contract — no double prefix, right index, clear mode semantics) → fix the P1 removeAll gate → confirm the stdin contract on real Windows (non-empty spool, correct event+tool) → add a test that catches argv↔VBS semantic drift.

…ent timeouts, VBS lifecycle

Review round on Tencent#596 (jeff-r2026), all points addressed:

- P0: the VBS launcher consumed Arguments(0) (the mode slot 'wait') as the
  dispatch event, so hooks dispatched 'teamai hook-dispatch wait' — an
  invalid event. The entry now passes [vbsPath, tail] and the VBS uses
  Arguments(1) (the raw dispatch command) directly — no hardcoded prefix,
  no mode arg, no double prefix.
- P1: removeAll now deletes teamai-hook-dispatch.vbs unconditionally
  (previously gated on content-differs, leaving an orphan on uninstall).
- The VBS spools ZCode's stdin payload to a temp file and feeds it to the
  dispatch via input redirection, preserving the STDIN contract for
  PostToolUse/UserPromptSubmit; per-event timeoutMs bounds the launch.
- POSIX entries keep bash -lc verbatim (platform branch restored — the
  unconditional wscript would have broken macOS/Linux on the next sync).
- Tests: payload asserted at args[2]; matcher-flag detection moved with it.

Validation (real box): two consecutive injects → still exactly 6 entries,
no duplicates; hidden launch verified end-to-end (session-start auto-pull
completed through the VBS chain).
…last-arg command extraction

The 961c1e3 template kept the hardcoded 'teamai hook-dispatch ' prefix in
the cmd line while entries already pass the full dispatch tail, doubling
the prefix: cmd split the tail into 'event=teamai' and every dispatch
failed (observed live: 'failed to parse STDIN JSON for event=teamai',
hook.run.failed on each run). The VBS now builds the cmd line from
Arguments(0) alone.

zcodeEntryCommand still assumed the d678c8d three-slot argv ([vbs, mode,
tail]) and returned hook.command ('wscript.exe') for the reverted
two-slot shape, so (a) entries written by the current code failed their
own managed-entry check and (b) legacy mode-slot entries were never
recognized for replacement — a reconcile appended duplicates alongside
the orphans. The command tail is always the LAST argv slot in both
generations; reading the last slot also restores team-command matching
against the managed-hooks manifest (no marker in team commands).

Verified end-to-end on Windows: reconcile replaced the 12 mixed-era
entries with the 6 current ones, and a piped payload through
cscript + VBS + cmd reached hook-dispatch with the correct event
(recorded in the dashboard).
… Windows launcher

Real-box verification of the VBS launcher found the ANSI-codepage round
trip breaks UTF-8 payloads containing multi-byte text at the first
non-ASCII sequence (quote swallowed / chars written as '?'), leaving
JSON.parse to fail. The degraded path already dispatches with {} and
exits 0, but the anonymous event lost its session and tool linkage.

parseStdin now regex-salvages the intact ASCII head — session_id,
tool_name, transcript_path, tool_use_id, cwd (snake_case and camelCase
variants; camelCase hits are mirrored onto the canonical snake_case
names handlers read) — so a degraded dispatch still lands on the right
session and tool in the dashboard. Verified end-to-end: a mangled
payload records 'tool_use for session <id> [tool=Bash]' instead of the
pid fallback.

Long-term fix tracked for the ZCode integration: the hook runner
spawning hook commands with windowsHide would let console commands
forward STDIN byte-exact and retire the launcher spool entirely.
@hc-tec

hc-tec commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Pushed two commits from real-box verification of the launcher — thanks again for the round-2 review; both P0s you called out were real.

ad02f74 — VBS runs the stored tail verbatim

  • Your P0 (argv↔VBS contract mismatch) was confirmed live, and in a worse form than predicted: the committed template still hardcoded the teamai hook-dispatch prefix while entries already pass the full dispatch tail, so every dispatch ran with a doubled prefix (event=teamai) and failed. The cmd line is now built from Arguments(0) alone.
  • Also fixed zcodeEntryCommand: it still assumed the three-slot argv from the earlier iteration, so the reverted two-slot shape failed its own managed-entry check — a reconcile appended duplicates alongside legacy orphans (observed live: 12 mixed-era entries). The command tail is always the LAST argv slot in both generations; reading the last slot also restores manifest matching for team commands, which carry no marker.

9f8e5f1 — salvage identity fields when STDIN JSON is mangled

  • Real-box data for your StdIn point: ASCII payloads round-trip perfectly, but payloads containing multi-byte text (we are a Chinese-language team) can break at the first non-ASCII sequence, because the launcher's StdIn.ReadAll() decodes through the ANSI codepage. In a day of real use roughly one in five dispatches degraded this way.
  • The degraded path already dispatches with {} and exits 0, but it dropped session and tool linkage. parseStdin now regex-salvages the intact ASCII head (session_id / tool_name / transcript_path / tool_use_id / cwd, snake_case and camelCase) so degraded events still land on the right session and tool in the dashboard. Content after the break is unrecoverable — that cost is inherent to any GUI-subsystem launcher that cannot forward raw STDIN.

One upstream thought: if the ZCode hook runner spawned hook commands with windowsHide, plain console commands could inherit STDIN byte-exact with no window flash, and the spool could be retired entirely for that host. Happy to simplify the ZCode path if that lands on their side.

Verified end-to-end on Windows: reconcile replaced the mixed-era entries with exactly the current set; clean and mangled payloads piped through the launcher reach hook-dispatch with correct events and identity. npx tsc --noEmit green; vitest green for the touched suites (zcode 12, hook-dispatch-cli 9).

Conflict resolution: upstream added the Copilot adapter in the same
region as toZcodeEntry. Copilot functions are kept; toZcodeEntry keeps
the PR's launcher signature (vbsPath) — upstream's interim direct-
command shape is what this PR replaces.
@jeff-r2026 jeff-r2026 self-assigned this Sep 17, 2026
@jeff-r2026

Copy link
Copy Markdown
Collaborator

P0s from last round look fixed on 1c7aab66. Still not mergeable:

  1. removeAll leaves the VBS. hooks.ts:718-725 only deletes when content differs; after a normal inject → remove it never runs. Delete unconditionally, and assert the file is gone. (await rmSync is a no-op — use fs/promises.rm.)
  2. wscript.exe is written on every platform. Injection is gated only on ~/.zcode existing, so POSIX users get their bash -lc entries replaced. Restore the win32 branch, or document ZCode as Windows-only. The PR body / 961c1e3 say POSIX keeps bash; HEAD doesn’t.
  3. Docs still say bash -lc. usage-guide.md and usage-guide.zh-CN.md — both, this PR.

Nit: assert the VBS uses Arguments(0) with no hardcoded prefix (shape-only tests missed event=wait / event=teamai). Happy to re-review after 1–3.

… docs

Review round 3 on Tencent#596 (jeff-r2026):

- removeAll now deletes teamai-hook-dispatch.vbs unconditionally: the
  delete previously sat inside a content-diff gate, so after a normal
  inject (file == template) the removal never fired and the script was
  left behind. Uses fs/promises rm instead of awaited rmSync.
- toZcodeEntry restores the win32/POSIX branch: injection is gated only
  on ~/.zcode existing, so the unconditional wscript entry replaced
  POSIX users' bash -lc entries. POSIX renders bash -lc like the other
  shell formats; the launcher script is only written on win32. The
  command tail stays the last argv slot on both branches, so
  zcodeEntryCommand's last-arg extraction covers both.
- usage-guide.md / usage-guide.zh-CN.md describe the actual entry
  shapes (VBS launcher on Windows, bash -lc on POSIX) instead of the
  stale bash-only wording.
- Tests: VBS content assertions (Arguments(0), no hardcoded dispatch
  prefix), launcher-gone assertion after removeAll, and
  platform-conditional shape assertions so the POSIX branch is covered
  on Linux CI.
…awn escape

Both additions landed in the same region of hook-dispatch-cli.ts and are
independent: the salvage covers mangled STDIN payloads at parse time;
Tencent#608's WMI path covers detached children killed by Windows job objects.
No behavior overlap.
@hc-tec

hc-tec commented Sep 18, 2026

Copy link
Copy Markdown
Contributor Author

All three points plus the nit are addressed in 2243a91 (branch also merged with current main, which brings in #608):

  1. removeAll deletes the VBS unconditionally — the delete previously sat inside the content-diff gate, so after a normal inject (file == template) it never fired. Also switched to fs/promises rm instead of the awaited rmSync. Added a test asserting the script is gone after removeAll.
  2. win32/POSIX branch restored in toZcodeEntry — POSIX renders plain bash -lc like the other shell formats and the launcher script is only written on win32. The command tail stays the LAST argv slot on both branches, so the last-arg extraction in zcodeEntryCommand covers both shapes and team-command manifest matching keeps working. Shape assertions in the tests are now platform-conditional so the POSIX branch is covered on Linux CI.
  3. Docs updated — usage-guide.md and usage-guide.zh-CN.md now describe the actual shapes (VBS launcher on Windows with per-event network-scale timeouts, plain bash -lc on POSIX, tail-as-last-argv invariant).

Nit: the win32 shape test now reads the written VBS and asserts it dispatches WScript.Arguments(0) with no hardcoded dispatch prefix — the content-level check that would have caught the doubled-prefix incident.

One note on the merge: #608's WMI escape landed in the same region of hook-dispatch-cli.ts as the STDIN salvage from 9f8e5f1; they're independent (salvage covers mangled payloads at parse time, WMI covers job-object-killed detached children) and both are kept.

@jeff-r2026 jeff-r2026 assigned jeff-r2026 and unassigned jeff-r2026 Sep 18, 2026
@github-actions

Copy link
Copy Markdown

Findings

  • [P1] Windows hooks cannot receive STDIN. src/hooks.ts:735 calls WScript.StdIn.ReadAll() under wscript.exe; the GUI host does not expose standard streams like cscript.exe. On Error Resume Next silently masks the resulting error, leaving an empty spool file. Hooks therefore lose cwd, session IDs, tool payloads, prompts, and transcript paths.
  • [P1] The launcher is blocking, contrary to the PR’s primary claim. src/hooks.ts:737 passes True as WScript.Shell.Run’s wait flag, so wscript.exe remains alive until hook-dispatch completes and ZCode waits for it. The test at src/__tests__/zcode.test.ts:79 only checks the argument shape and cannot detect this.
  • [P2] Hook status ignores the required launcher file. src/hooks.ts:1105 reports installed solely from config.json; it does not verify that teamai-hook-dispatch.vbs exists or matches the managed template. A deleted, stale, or quarantined script therefore leaves broken hooks reported as healthy.

Testing

  • The PR description includes unit/type/build results and a concrete Windows real-CLI dogfood record, so it satisfies the review rule requiring an e2e record. However, that validation did not catch the blocking and missing-STDIN behavior above.

Automated review finding: the zcode branch of getHookStatus reported
'installed' from config.json alone, so a deleted, stale, or AV-
quarantined teamai-hook-dispatch.vbs left dead hooks reported as
healthy. The launcher file is now required on win32 (POSIX entries are
plain bash and have no launcher).
@hc-tec hc-tec changed the title fix(zcode): launch hooks via hidden wscript VBS — no console flash, non-blocking fix(zcode): launch hooks via hidden wscript VBS — no console flash, bounded wait Sep 18, 2026
@hc-tec

hc-tec commented Sep 18, 2026

Copy link
Copy Markdown
Contributor Author

Responding to the automated review findings (all three checked against the real-box instrumentation from the earlier rounds):

[P1] "Windows hooks cannot receive STDIN — empty spool" — false positive. WScript.StdIn reads piped stdin under wscript.exe fine (the limitation applies to console stdin, not a pipe). Real-box evidence: the STDIN-degradation log lines from 9f8e5f1 show the spool contents hook-dispatch received — multi-KB bodies (6,626 / 4,438 / 77,494 bytes) that traveled through exactly this StdIn.ReadAll() → spool path; and a full day of live sessions produced correctly-attributed records through the same chain. An empty spool would have produced neither. Worth a real-box test before trusting this one either way — that is exactly what the round-2 round-trip concluded.

[P1] "The launcher is blocking" — accurate about the mechanism, intended by design. bWaitOnReturn = True bounds the host stall to the per-event timeout (network-scale: 180s session start, 60s stop/prompt, 30s post-tool-use); measured dispatch latency is ~100-300ms per hook. This is the outcome of the round-1 review — the original wait=False-everywhere shape was replaced with a per-event bounded wait. Concretely misleading was the PR title claiming "non-blocking" — retitled to "bounded wait".

[P2] "status ignores the launcher file" — valid, fixed in 0cf0147. getHookStatus now requires the launcher file on win32, so a deleted, stale, or AV-quarantined script reports missing instead of installed-with-dead-entries. Covered by a test (script removed → missing).

@jeff-r2026
jeff-r2026 merged commit bea46d1 into Tencent:main Sep 18, 2026
8 checks passed
Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
…ounded wait (Tencent#596)

Windows ZCode hook entries launch through wscript.exe running a hidden
teamai-hook-dispatch.vbs written next to config.json, eliminating the
console-window flash on every hook run. The launcher spools STDIN to a
temp file to preserve the payload contract and runs the dispatch with a
per-event bounded wait (SessionStart 180s, Stop/UserPromptSubmit 60s,
PostToolUse 30s). POSIX entries keep bash -lc. Identity fields are
salvaged when a multi-byte payload degrades at the ANSI-codepage spool
step, and getHookStatus requires the launcher on win32.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants