Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
144 commits
Select commit Hold shift + click to select a range
c43f73f
feat(web): loud blocked session-list chrome + off-viewport counter (#…
heavygee Aug 29, 2026
59152f8
fix(web): bail out of the blocked off-viewport measure when unchanged
heavygee Aug 29, 2026
2fa1ab9
feat(web): count prompt-parked agents as blocked (#1717)
heavygee Aug 29, 2026
3287b66
feat(web): cover every blocker class, and make new ones announce them…
heavygee Aug 31, 2026
a181bf7
feat: mark a session unblocked by hand, with a recorded reason (#1717)
heavygee Sep 1, 2026
3662919
fix(web,hub): address cold-review findings on blocked chrome (#1717)
heavygee Nov 11, 2026
030d5ca
fix(web): archived prompts stop blocking; reserve toolbar width (#1717)
heavygee Nov 11, 2026
093edd2
fix(web,hub): second cold-review round on blocked chrome (#1717)
heavygee Nov 19, 2026
3215177
fix(web,hub): carry the blocked footer through a merge; scope blocked…
heavygee Nov 19, 2026
2324332
fix(hub): reconcile notify on OpenCode rewind; ignore unsent schedule…
heavygee Nov 19, 2026
0148d20
fix(hub): do not resurrect an answered footer when merging sessions (…
heavygee Nov 19, 2026
c5cd784
fix(hub): ignore subagent footers; bound a cleared notify by its turn…
heavygee Nov 19, 2026
d347f2f
fix(web,hub): address upstream review on blocked chrome (#1717)
heavygee Nov 19, 2026
bdc18fc
fix(web,hub): second upstream review round; fix settings lock orderin…
heavygee Nov 19, 2026
847b5c7
fix(web,hub): give the blocked acknowledgement an identity (#1717)
heavygee Nov 19, 2026
2bac56a
fix(web,hub): acknowledgements become a set; delivery must actually d…
heavygee Nov 19, 2026
8ab5173
fix(hub,web): v26 upgrade skipped the new columns; blocker identity h…
heavygee Nov 19, 2026
a67af12
fix(hub,web): clock-domain boundary, overflow identity, swept-reply m…
heavygee Nov 19, 2026
86f4867
fix(web): preserve the uncapped request ids in stale-snapshot reconci…
heavygee Nov 19, 2026
48739a6
fix(web,hub): order the blocked clear by seq, not by two clocks (#1717)
heavygee Nov 19, 2026
51fe4a0
fix(web,hub): give delivery a hub-domain position of its own (#1717)
heavygee Nov 19, 2026
a22a65a
refactor(hub): apply the sibling-path audit to the notify ordering (#…
heavygee Nov 19, 2026
2418abe
fix(web,hub): order the blocked clear by hub arrival, not by position…
heavygee Nov 19, 2026
867f8cb
docs(hub): correct comments describing the deleted seq ordering (#1717)
heavygee Nov 20, 2026
b3307de
fix(web,hub): keep hub arrival across the socket hop and the import p…
heavygee Nov 20, 2026
414c955
test(hub): cover what counts as an answer, and let the sweep say so (…
heavygee Nov 20, 2026
7fc8be2
fix(web,hub): stamp imported rows in the transcript's own clock (#1717)
heavygee Nov 20, 2026
367bab5
fix(web,hub): order imported rows by transcript position, not arrival…
heavygee Nov 20, 2026
b575ae5
fix(web,hub): reserve the author cutoff for clocks that can discrimin…
heavygee Nov 20, 2026
df19b5b
fix(web,hub): separate an exact replay from a tie the clock cannot br…
heavygee Nov 20, 2026
793be76
fix(web,hub): take replay identity from the message, not its text (#1…
heavygee Nov 20, 2026
8254b8c
fix(hub,web): withdraw the delivery-evidence transfer, keep the occur…
heavygee Nov 20, 2026
91e7ab2
fix(hub,web): match imported occurrences by native transcript id (#1717)
heavygee Nov 20, 2026
a6987f6
fix(cli,hub,web): a maintenance ack is not an answer; align merge occ…
heavygee Nov 20, 2026
a4f33ea
fix(cli,hub): keep the ordinary ack shape; align mirrors; spare maint…
heavygee Nov 20, 2026
68d2905
fix(hub): forward the maintenance callback; make merge alignment orde…
heavygee Nov 20, 2026
95e7a08
fix: round 21's four findings, batched (#1717)
heavygee Nov 20, 2026
0a128bf
fix: round 22's two Majors and two Minors, batched (#1717)
heavygee Nov 20, 2026
459a09e
fix: round 23's two Majors and two Minors — stop inferring provenance…
heavygee Nov 20, 2026
243b18d
fix: historical imported rows read as unknown, not live (#1717)
heavygee Nov 20, 2026
67b81e7
Merge remote-tracking branch 'upstream/main' into feat/blocked-sessio…
heavygee Nov 20, 2026
84a8184
fix: round 24's Major and four Minors — preserve relation when values…
heavygee Nov 20, 2026
ec8ed5b
fix(web,hub): round 25 cold-review — close 5 remaining structural gap…
heavygee Nov 20, 2026
471695a
fix(hub): round 25's own dismissal-cap test timed out on CI (#1717)
heavygee Nov 20, 2026
62560da
fix(hub,web,shared): round 26 cold-review — close 6 findings + enumer…
heavygee Nov 20, 2026
3a4ce60
fix(hub,web,shared): close the incremental-patch cell of the thinking…
heavygee Nov 20, 2026
ae5ac03
fix(hub,web,shared): thinkingAt is not a monotonic revision — use a h…
heavygee Nov 20, 2026
a42f670
fix(web): keyboard focus disappeared from a jump-revealed row before …
heavygee Nov 20, 2026
eeac97c
fix(shared): request-ref truncation had no awareness of kind, droppin…
heavygee Nov 20, 2026
bf190f7
fix(hub): startup notify backfill permanently skipped recently-active…
heavygee Nov 20, 2026
62b88d9
fix(hub): revert Codex Desktop merge row-survival changes; reconcile …
heavygee Nov 23, 2026
9b2bbc8
fix(hub): cross-session notify selection compared an untimestamped im…
heavygee Nov 23, 2026
ed0bbac
fix(hub): drop the imported/reconciled_invoked_at columns this PR add…
heavygee Nov 23, 2026
5edd56e
fix(hub): document the sessionIds ordering contract reconcileNotifyAc…
heavygee Nov 23, 2026
4203f99
Merge remote-tracking branch 'refs/remotes/upstream/main' into feat/b…
heavygee Nov 23, 2026
1d08876
fix(hub): three real bugs in the cross-session notify reconciliation,…
heavygee Nov 23, 2026
29f1035
fix(web): thinkingRevision resets to 0 on a hub restart, and pendingR…
heavygee Nov 23, 2026
79b2abd
fix(web): don't block on a stuck cached thinking flag or a non-blocki…
heavygee Nov 23, 2026
6324a99
fix(web): re-add a selected session the list filter dropped (#1717)
heavygee Nov 23, 2026
fc5951a
fix(e2e): exercise the actual off-screen-collapsed scroll path, regis…
heavygee Nov 23, 2026
9f582f5
fix(web): persist a thinkingRevision-only move into the list cache (#…
heavygee Nov 23, 2026
47a5f00
fix(hub): stop a session's own already-answered footer from silencing…
heavygee Nov 23, 2026
1071634
fix(hub,web): detect a hub restart directly instead of only inferring…
heavygee Nov 23, 2026
cfd273f
fix(shared): prioritize a genuine blocking request over non-blocking …
heavygee Nov 23, 2026
e7f2a2f
fix(web): restore the selected session from a base the status filter …
heavygee Nov 23, 2026
271b02e
fix(e2e): assert the actual up-jump target, not the first blocked row…
heavygee Nov 23, 2026
141d0fd
fix(hub): carry a dismissed duplicate's ack forward when its OWN foot…
heavygee Nov 23, 2026
f7a46b4
fix(hub,web): carry hubGeneration through the SSE path, not just the …
heavygee Nov 23, 2026
65d39d3
fix(web): order collapsed-section blockers against mounted rows by ac…
heavygee Nov 23, 2026
8055bad
fix(hub): page the startup notify backfill scan past its fixed 6-row …
heavygee Nov 23, 2026
aad19a6
fix(hub): decline cross-session footer/dismissal matching by content …
heavygee Nov 23, 2026
a60cec9
fix(hub): page the notify backfill scan until a reply is established,…
heavygee Nov 23, 2026
f7f6c42
fix(web): read hubGeneration off the cached row, not a connection-lev…
heavygee Nov 23, 2026
b53277d
fix(hub): keep a later blocker from a shorter Codex duplicate (#1717)
heavygee Nov 23, 2026
74b1e88
fix(hub): read enough history to identify an answered replay (#1717)
heavygee Nov 23, 2026
aa95fc6
fix(hub): preserve a stored footer when the agent resumes an interrup…
heavygee Nov 23, 2026
c90cfb5
fix(web): order revision zero within the same hub generation (#1717)
heavygee Nov 23, 2026
ecb83f2
Merge remote-tracking branch 'upstream/main' into feat/blocked-sessio…
heavygee Nov 28, 2026
36c4b53
fix(hub): update migration log assertion for this branch's SCHEMA_VER…
heavygee Nov 28, 2026
d3a9113
fix(hub): keep an unanswered blocker when a stale Codex import ends i…
heavygee Nov 28, 2026
67e4dd8
fix(hub): recover blockers beyond the startup scan limit (#1717)
heavygee Nov 28, 2026
c9852bb
fix(web): preserve newer connection state when rejecting a stale list…
heavygee Nov 28, 2026
98a6085
Merge remote-tracking branch 'upstream/main' into feat/blocked-sessio…
heavygee Nov 30, 2026
cf384d3
fix(hub): yield to the event loop between sessions during startup not…
heavygee Nov 30, 2026
3cb7e8c
fix(hub): recover a newer source footer a merge shifted to a lower se…
heavygee Nov 30, 2026
87b10bd
fix(hub): keep an unresolved blocker visible when merging Codex dupli…
heavygee Nov 30, 2026
39ee5ed
fix(hub): preserve blocker timing and delivery state when copying for…
heavygee Nov 30, 2026
65bfc4c
fix(web): unlock blocker audio from a user gesture, and stop silently…
heavygee Nov 30, 2026
4a164fa
fix(hub): exclude a synthetic collision settlement from merge reply e…
heavygee Nov 30, 2026
37dfd36
fix(hub): keep a canonical dismissal from hiding a distinct merged fo…
heavygee Nov 30, 2026
87b1db4
fix(hub): bound the startup backfill's unbounded fallback within a tr…
heavygee Nov 30, 2026
f1f42ac
fix(web): unlock saved sound mode on touch release and keyboard activ…
heavygee Nov 30, 2026
49dad54
fix(shared): scope non-blocking classification to Codex's async quest…
heavygee Nov 30, 2026
d536713
fix(hub): clear a dismissal entirely rather than leaving an empty key…
heavygee Nov 30, 2026
68990dc
fix(hub): discard a chunked backfill scan that spans a concurrent rewind
heavygee Nov 30, 2026
b2ae9e9
fix(web): keep audio unlock listeners through touch activation
heavygee Nov 30, 2026
8944ef5
fix(hub): scope a stale canonical dismissal to the footer it actually…
heavygee Nov 30, 2026
5e38a2a
fix(hub): preserve confirmed delivery time when a merge clears a loca…
heavygee Nov 30, 2026
3d1e3ad
fix(hub): retry a chunked backfill scan invalidated by an unrelated e…
heavygee Nov 30, 2026
25029fa
docs(hub): warn that workGraphNotifyIngest.ts carries deliberate NUL …
heavygee Nov 30, 2026
4bbf67b
fix(hub): use native message identity, not content, to scope a canoni…
heavygee Nov 30, 2026
45e0222
fix(hub): defer a canonical dismissal edit until the duplicate merge …
heavygee Nov 30, 2026
8f59d03
fix(web): keep a jump-revealed row visible while its action menu is open
heavygee Nov 30, 2026
712a747
fix(hub): apply the winning dismissal transfer after its own strip, n…
heavygee Nov 30, 2026
fe4c937
fix(web): prefer a measured off-screen row when the jump pill points …
heavygee Nov 30, 2026
d20d95d
fix(cli): send clearQueuedThinkingGrace from Claude's bare /plan hand…
heavygee Nov 30, 2026
3545dda
fix(web): keep content search stable across revision-only keepalives
heavygee Nov 30, 2026
1737d18
fix(web): render content-search hits from the live session, not the f…
heavygee Nov 30, 2026
e8d502f
fix(web): refetch content search when a candidate's transcript grows …
heavygee Nov 30, 2026
0d8c5f8
fix(web): refetch content search on a new operator prompt too (#1717)
heavygee Nov 30, 2026
27dfe01
fix(hub): reject a reason-only blocked-ack once a keyed dismissal exi…
heavygee Nov 30, 2026
464c0bb
Merge upstream/main into feat/blocked-session-affordance-1717
heavygee Dec 1, 2026
05d78d0
Merge upstream/main into feat/blocked-session-affordance-1717
heavygee Dec 1, 2026
b8ee9c0
Merge upstream/main into feat/blocked-session-affordance-1717
heavygee Dec 2, 2026
09bd717
Merge upstream/main into feat/blocked-session-affordance-1717
heavygee Dec 2, 2026
6a4e7f7
Merge upstream/main into feat/blocked-session-affordance-1717
heavygee Dec 2, 2026
c5a663e
fix(web): give each session one render location across groups and Blo…
heavygee Dec 2, 2026
094c151
Merge upstream/main into feat/blocked-session-affordance-1717
heavygee Dec 2, 2026
1e47587
feat(ios): support session groups, dissolve group, and /sessions link…
tiann Dec 3, 2026
bec9f71
feat(ios): cross-paragraph text selection, zoomable image viewer, quo…
tiann Dec 3, 2026
40a2a9d
feat: fold session group members into the leader row
tiann Dec 3, 2026
e82313c
Merge upstream/main into feat/blocked-session-affordance-1717
heavygee Dec 3, 2026
66ed3e8
feat(ios): add chat status chrome, streaming markdown cache, hardware…
tiann Dec 3, 2026
e161ef1
feat(ios): add dictation UX, diff review comments, content search, sk…
tiann Dec 3, 2026
58523e9
feat(ios): make project groups default and collapsible, and contain p…
tiann Dec 3, 2026
8e42533
feat(web): align project group headers and disambiguation with iOS style
tiann Dec 3, 2026
7d0aa46
Merge remote-tracking branch 'upstream/main' into feat/blocked-sessio…
heavygee Dec 3, 2026
06d0ea9
feat(push,pairing): add per-device push preferences, hubId routing, a…
tiann Dec 3, 2026
2ed76d5
Release version 0.37.1
tiann Dec 3, 2026
ac90ffc
Merge remote-tracking branch 'upstream/main' into feat/blocked-sessio…
heavygee Dec 3, 2026
5b5d7da
feat(ios): quiet session group rows and nest members compactly
tiann Dec 3, 2026
dca1732
feat(ios): add native remote terminal
tiann Dec 3, 2026
28e33e0
fix(ios): size wrapped table rows and align nested and numbered lists
tiann Dec 3, 2026
310bc53
merge: iOS session group row polish (quiet colours, compact members)
tiann Dec 3, 2026
0fefcc8
fix(cli): mask every non-allowlisted settings field in hapi doctor (#…
Duang777 Dec 4, 2026
ccf0fef
fix(cli): keep argv out of npm launcher failure output (#2766)
Duang777 Dec 4, 2026
59faec2
fix(hub): an update sent without an acknowledgement no longer takes t…
miuiadmin Dec 4, 2026
c19b731
fix(cli): keep job attach watching when a Windows liveness probe fail…
Duang777 Dec 4, 2026
2ced8b8
fix(hub): keep duplicate merge consistent when a later delete is refu…
arsalankhan786777 Dec 4, 2026
7229e06
fix: reject model and effort changes a locally driven session cannot …
junmo-kim Dec 4, 2026
925e64f
fix(agy): clear the HAPI MCP URL when the ACP launcher stops (#2504)
junmo-kim Dec 4, 2026
a0a826d
fix(cli): never let the agy quota probe start interactive sign-in (#2…
junmo-kim Dec 4, 2026
de296b5
Merge remote-tracking branch 'upstream/main' into feat/blocked-sessio…
heavygee Dec 4, 2026
39626b4
feat(web): fold blocked lens into combined session list filters
heavygee Nov 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
1 change: 1 addition & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ jobs:
image-preview-back.spec.ts
opencode-fork-buttons.spec.ts
auth-network-recovery.spec.ts
session-list-blocked.spec.ts
# playwright.config.ts already sets `trace: 'retain-on-failure'` and
# the html reporter on CI, but nothing collected the output, so every
# trace died with the runner — leaving CI-only Playwright failures
Expand Down
2 changes: 1 addition & 1 deletion android/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ android {
targetSdk = 36
versionCode = gitCommitCount ?: 1
// Tracks the hapi CLI/hub release train.
versionName = providers.gradleProperty("hapiVersionName").orElse("0.37.0").get()
versionName = providers.gradleProperty("hapiVersionName").orElse("0.37.1").get()
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@ object PairingLinks {
fun parse(raw: String): BindLink? = BindLink.parse(raw) ?: parseWebUrl(raw)

/**
* Parses the web direct-access QR: any absolute HTTPS URL whose query
* carries non-blank `hub` (itself an HTTPS URL) and `token` params. The
* host is deliberately not pinned to `app.hapi.run` — self-hosters may
* serve the web app from their own origin. Returns null otherwise.
* Parses the web direct-access QR: any absolute HTTPS URL whose fragment
* (preferred) or query carries non-blank `hub` (itself an HTTPS URL) and
* `token` params. The host is deliberately not pinned to `app.hapi.run` —
* self-hosters may serve the web app from their own origin. Returns null
* otherwise.
*/
fun parseWebUrl(raw: String): BindLink? {
val uri = try {
Expand All @@ -38,9 +39,18 @@ object PairingLinks {
if (scheme != "https") return null
if ((uri.host ?: uri.authority).isNullOrBlank()) return null

val params = BindLink.parseFormQuery(uri.rawQuery ?: return null) ?: return null
val hub = params["hub"]?.takeIf { it.isNotBlank() } ?: return null
val token = params["token"]?.takeIf { it.isNotBlank() } ?: return null
val fragmentParams = uri.rawFragment?.takeIf { it.isNotEmpty() }?.let {
BindLink.parseFormQuery(it) ?: return null
}
val queryParams = uri.rawQuery?.takeIf { it.isNotEmpty() }?.let {
BindLink.parseFormQuery(it) ?: return null
}
if (fragmentParams == null && queryParams == null) return null

val hub = (if (fragmentParams != null && "hub" in fragmentParams) fragmentParams["hub"] else queryParams?.get("hub"))
?.takeIf { it.isNotBlank() } ?: return null
val token = (if (fragmentParams != null && "token" in fragmentParams) fragmentParams["token"] else queryParams?.get("token"))
?.takeIf { it.isNotBlank() } ?: return null
if (!BindLink.isHttpsUrl(hub)) return null
return BindLink(hubUrl = hub, accessToken = token)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,31 @@ class PairingLinksTest {
assertNull(PairingLinks.parse("https://example.com/some/page"))
assertNull(PairingLinks.parse("hello world"))
}

@Test
fun `parse accepts the fragment web direct-access form and prefers fragment over query`() {
val fragmentOnly = PairingLinks.parse(
"https://app.hapi.run/#hub=https%3A%2F%2Fdemo.hapi.run&token=tok_9f8%3Adefault"
)
assertEquals(BindLink(hubUrl = "https://demo.hapi.run", accessToken = "tok_9f8:default"), fragmentOnly)

val mixed = PairingLinks.parse(
"https://app.hapi.run/?hub=https%3A%2F%2Fdemo.hapi.run#token=frag_tok"
)
assertEquals(BindLink(hubUrl = "https://demo.hapi.run", accessToken = "frag_tok"), mixed)

val overridden = PairingLinks.parse(
"https://app.hapi.run/?hub=https%3A%2F%2Fquery.example.com&token=query_tok#hub=https%3A%2F%2Ffrag.example.com&token=frag_tok"
)
assertEquals(BindLink(hubUrl = "https://frag.example.com", accessToken = "frag_tok"), overridden)

assertNull(
PairingLinks.parse(
"https://app.hapi.run/?hub=https%3A%2F%2Fquery.example.com&token=query_tok#token="
)
)
assertNull(
PairingLinks.parse("https://app.hapi.run/#hub=https%3A%2F%2Fdemo.hapi.run&token=%zz")
)
}
}
2 changes: 1 addition & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 13 additions & 51 deletions cli/bin/hapi.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -65,56 +65,28 @@ function getBinaryPath(platformName = platform, archName = arch) {
return path.join(path.dirname(pkgPath), 'bin', binName);
}

function formatCommand(binPath, args) {
return [binPath, ...args].map((arg) => JSON.stringify(String(arg))).join(' ');
}

/**
* Any `hapi [ -- ] job … -- <workload>` argv can carry tokens in flags /
* shell -c text. Binary strips one leading runtime `--` (cliArgs); parser
* also accepts flags before the action word. Keep CLI diagnostics (stdio
* inherit), but never echo workload args from the npm launcher.
*/
function jobWorkloadSeparatorIndex(args) {
if (!Array.isArray(args) || args.length === 0) {
return -1;
}
let commandIndex = 0;
if (args[0] === '--') {
commandIndex = 1;
}
if (args[commandIndex] !== 'job') {
return -1;
}
const separator = args.indexOf('--', commandIndex + 1);
if (separator === -1 || separator === args.length - 1) {
return -1;
}
return separator;
}

function displayArgsForFailure(args) {
const separator = jobWorkloadSeparatorIndex(args);
if (separator === -1) {
return args;
}
return args.slice(0, separator + 1).concat(['<workload>']);
}

function normalizeExecError(error) {
return {
status: typeof error?.status === 'number' ? error.status : null,
signal: typeof error?.signal === 'string' ? error.signal : null,
message: error?.message ? String(error.message) : null,
code: typeof error?.code === 'string' ? error.code : null,
};
}

/**
* argv can carry secrets (tokens in flags, `job run -- <workload>` text), and
* Node's exec error message repeats the whole command line. Print only the
* binary path, why it failed, and its exit status or signal; the binary's own
* diagnostics already reached stderr through stdio: 'inherit'.
*/
function reportExecutionFailure(error, binPath, args, log = console.error) {
const { status, signal, message } = normalizeExecError(error);
const displayArgs = displayArgsForFailure(args);
const omitRawExecMessage = jobWorkloadSeparatorIndex(args) !== -1;
const { status, signal, code } = normalizeExecError(error);

log(`Failed to execute: ${formatCommand(binPath, displayArgs)}`);
log(`Failed to execute: ${JSON.stringify(String(binPath))}`);

if (code) {
log(`Binary could not be started: ${code}.`);
}

if (signal) {
log(`Binary terminated by signal ${signal}.`);
Expand All @@ -124,13 +96,6 @@ function reportExecutionFailure(error, binPath, args, log = console.error) {
log(`Binary exited with status ${status}.`);
}

// Token-by-token redaction of Node's argv-bearing message is unsafe when a
// short flag overlaps a longer credential arg. For job + workload argv,
// drop the raw message entirely — CLI diagnostics already went to stderr.
if (message && !omitRawExecMessage) {
log(message);
}

return { status, signal };
}

Expand Down Expand Up @@ -221,12 +186,9 @@ if (require.main === module) {
}

module.exports = {
displayArgsForFailure,
formatCommand,
getPlatformKey,
getBinaryPath,
isSupportedPlatform,
jobWorkloadSeparatorIndex,
normalizeExecError,
reportExecutionFailure,
reportMissingPlatformPackage,
Expand Down
2 changes: 1 addition & 1 deletion cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@twsxtd/hapi",
"version": "0.37.0",
"version": "0.37.1",
"description": "App for agentic coding - access coding agent anywhere",
"author": "Kirill Dubovitskiy & weishu",
"license": "AGPL-3.0-only",
Expand Down
147 changes: 147 additions & 0 deletions cli/src/agent/agentQuotas.spawnArgs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { EventEmitter } from 'node:events'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const spawnMock = vi.hoisted(() => vi.fn())
vi.mock('node:child_process', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:child_process')>()
return { ...actual, spawn: spawnMock }
})

const killMock = vi.hoisted(() => vi.fn())
vi.mock('@/utils/process', () => ({ killProcessByChildProcess: killMock }))

import * as agentAvailability from './agentAvailability'
import { _resetAgentQuotasCacheForTests, probeAgyQuota } from './agentQuotas'

const USAGE_JSON = JSON.stringify({ command: { name: 'usage', data: { groups: [] } } })
const CREDITS_JSON = JSON.stringify({ command: { name: 'credits', data: { remaining_credits: 10 } } })

type SpawnCall = { command: string; args: string[] }

function respondingChild(output: string) {
const child = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
kill: vi.fn()
})
queueMicrotask(() => {
child.stdout.emit('data', `${output}\n`)
child.emit('close', 0)
})
return child
}

describe('agy quota subprocess arguments', () => {
beforeEach(() => {
_resetAgentQuotasCacheForTests()
spawnMock.mockReset()
vi.spyOn(agentAvailability, 'getAgentAvailability').mockImplementation((agent) => ({
agent,
available: agent === 'agy'
}))
})

it('sends models, usage, and credits as separate calls with their full arguments', async () => {
const calls: SpawnCall[] = []
spawnMock.mockImplementation((command: string, args: string[]) => {
calls.push({ command, args })
if (args[0] === 'models') return respondingChild('gemini-3-pro')
if (args[1] === '/usage') return respondingChild(USAGE_JSON)
if (args[1] === '/credits') return respondingChild(CREDITS_JSON)
throw new Error(`Unexpected agy arguments: ${args.join(' ')}`)
})

const result = await probeAgyQuota({})

expect(result.status).toBe('ok')
expect(calls).toEqual([
{ command: 'agy', args: ['models'] },
{ command: 'agy', args: ['-p', '/usage', '--output-format', 'json'] },
{ command: 'agy', args: ['-p', '/credits', '--output-format', 'json'] }
])
})

it('starts usage and credits together after models within the shared probe budget', async () => {
vi.useFakeTimers()
killMock.mockResolvedValue(false)
const spawnTimes: number[] = []
spawnMock.mockImplementation((_command: string, args: string[]) => {
spawnTimes.push(Date.now())
const child = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
kill: vi.fn()
})
const output = args[0] === 'models' ? 'gemini-3-pro' : args[1] === '/usage' ? USAGE_JSON : null
if (output) {
setTimeout(() => {
child.stdout.emit('data', `${output}\n`)
child.emit('close', 0)
}, 4_000)
}
return child
})

try {
const startedAt = Date.now()
const probe = probeAgyQuota({})
await vi.advanceTimersByTimeAsync(4_000)
expect(spawnTimes).toHaveLength(3)
expect(spawnTimes[1] - startedAt).toBe(4_000)
expect(spawnTimes[2] - startedAt).toBe(4_000)

const settled: { result?: Awaited<ReturnType<typeof probeAgyQuota>>; at?: number } = {}
void probe.then((value) => {
settled.result = value
settled.at = Date.now()
})
await vi.advanceTimersByTimeAsync(5_000)
expect(settled.result).toBeDefined()
expect(settled.result?.status).toBe('ok')
expect(settled.at).toBe(startedAt + 9_000)
} finally {
vi.useRealTimers()
killMock.mockReset()
}
})

it('returns a usage error before a hung credits command settles', async () => {
vi.useFakeTimers()
killMock.mockResolvedValue(false)
const creditsChildren: EventEmitter[] = []
spawnMock.mockImplementation((_command: string, args: string[]) => {
const child = Object.assign(new EventEmitter(), {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
kill: vi.fn()
})
if (args[0] === 'models') {
queueMicrotask(() => {
child.stdout.emit('data', 'gemini-3-pro\n')
child.emit('close', 0)
})
} else if (args[1] === '/usage') {
queueMicrotask(() => {
child.stdout.emit('data', 'not quota json\n')
child.emit('close', 0)
})
} else {
creditsChildren.push(child)
}
return child
})

try {
const startedAt = Date.now()
const result = await probeAgyQuota({})

expect(result.status).toBe('error')
expect(result.note).toBe('Unable to parse Antigravity quota output')
expect(Date.now() - startedAt).toBe(0)
expect(creditsChildren).toHaveLength(1)
} finally {
vi.useRealTimers()
killMock.mockReset()
}
})
})
Loading