merge: hapi upstream v0.36.5

Adopt fork preview/boundary and branch endpoints, GitHub PR awareness,
session external refs, queue batch aliases and the attached runtime's
history validation. The fork keeps its Session List/Row/Chat surfaces,
Claude/DSH import dialogs, goal controls and DSH Web runtime.

Notable resolutions:
- Codex projection compares replay payload identity while still carrying the
  fork's Hub persistence options; queue committed() now uses upstream's batch
  alias matching
- user messages are ACKed per accepted batch member, with the fork's replay
  createdAt/verifyPersistence path retained
- server keeps the fork's public studio/share middleware and one gzip
  middleware; upstream's static cache headers and HEAD handling are adopted
- settings keeps the fork's session-summary/teams/unavailable-agents rows and
  adds GitHub PR awareness
- iOS keeps the personal bundle id and local string catalog (Japanese catalog
  from upstream is not merged)

Validation: typecheck passes; suite 5971 pass, failures limited to the four
machine-specific macOS responsibility probes.

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
2026-11-20 13:33:58 +08:00
co-authored by HAPI Claude Code
498 changed files with 37368 additions and 12951 deletions
+206 -2
View File
@@ -9,6 +9,118 @@ describe('MessageQueue2', () => {
expect(queue.isClosed()).toBe(false);
});
it('answers in-flight for a dequeued-but-uncommitted localId so a Cancel holds the row busy instead of double-delivering', async () => {
// Round-7 cross-review §3.1 sequence A: with the ACK deferred to the
// dispatch commit, a Cancel landing inside the dequeue→commit window
// used to answer false ('not-found'), which pushed the hub row to
// indeterminate and let a Retry re-emit the message → delivered twice.
const queue = new MessageQueue2<string>(mode => mode);
const consumed: string[][] = [];
queue.onBatchConsumed = (ids) => { consumed.push([...ids]); };
queue.push('M', 'local', 'L');
const batch = await queue.waitForDeferredBatch();
expect(batch?.items.map(item => item.localId)).toEqual(['L']);
expect(consumed).toEqual([]);
// Cancel inside the window: the row is neither queued nor reserved.
expect(queue.cancelByLocalId('L')).toBe('in-flight');
// The commit lands after the cancel attempt: the message is delivered
// exactly once, the hub row goes invoked, and the in-flight mark is
// cleared immediately even while the queue stays idle.
queue.commitBatch(batch!);
expect(consumed).toEqual([['L']]);
expect(queue.cancelByLocalId('L')).toBe(false);
// A retry re-emit with the same localId must still be cancellable —
// both while queued and when reserved via takeByLocalId.
queue.push('M again', 'local', 'L');
expect(queue.cancelByLocalId('L')).toBe(true);
expect(queue.size()).toBe(0);
queue.push('M reserved', 'local', 'L');
expect(queue.takeByLocalId('L')).not.toBeNull();
expect(queue.cancelByLocalId('L')).toBe(true);
expect(queue.size()).toBe(0);
});
it('keeps answering in-flight for repeated cancels while the batch is still uncommitted', async () => {
// Round-7 cross-review §3.1 sequence B: a second Cancel on the
// indeterminate row must not read 'not-found' (the hub would delete
// the row while the CLI still dispatches it — delivered after an
// explicit cancel). Until the commit settles, the answer stays
// 'in-flight'.
const queue = new MessageQueue2<string>(mode => mode);
queue.push('M', 'local', 'L');
await queue.waitForDeferredBatch();
expect(queue.cancelByLocalId('L')).toBe('in-flight');
expect(queue.cancelByLocalId('L')).toBe('in-flight');
// Terminal hygiene: resetting the queue clears the in-flight marks.
queue.reset();
expect(queue.cancelByLocalId('L')).toBe(false);
});
it('clears in-flight tracking when a deferred batch is dropped via releaseBatch', async () => {
const queue = new MessageQueue2<string>(mode => mode);
const consumed: string[][] = [];
queue.onBatchConsumed = (ids) => { consumed.push([...ids]); };
queue.push('M', 'local', 'L');
const batch = await queue.waitForDeferredBatch();
expect(queue.cancelByLocalId('L')).toBe('in-flight');
queue.releaseBatch(batch!);
expect(consumed).toEqual([]);
expect(queue.cancelByLocalId('L')).toBe(false);
queue.push('M retry', 'local', 'L');
expect(queue.takeByLocalId('L')).not.toBeNull();
expect(queue.cancelByLocalId('L')).toBe(true);
});
it('never marks non-deferred waitForMessagesAndGetAsString batches as in-flight (opencode, claude, agy)', async () => {
const queueWithAck = new MessageQueue2<string>(mode => mode);
const consumed: string[][] = [];
queueWithAck.onBatchConsumed = (ids) => { consumed.push([...ids]); };
queueWithAck.push('M1', 'local', 'L1');
await queueWithAck.waitForMessagesAndGetAsString();
expect(consumed).toEqual([['L1']]);
expect(queueWithAck.cancelByLocalId('L1')).toBe(false);
const queueWithoutAck = new MessageQueue2<string>(mode => mode);
queueWithoutAck.push('M2', 'local', 'L2');
await queueWithoutAck.waitForMessagesAndGetAsString();
expect(queueWithoutAck.cancelByLocalId('L2')).toBe(false);
});
it('unshiftBatch restores a dequeued batch in original order with localIds intact and no extra ACK', async () => {
const queue = new MessageQueue2<string>(mode => mode);
const consumed: string[][] = [];
queue.onBatchConsumed = ids => { consumed.push(ids); };
queue.push('a', 'local', 'id-a');
queue.push('b', 'local', 'id-b');
const batch = await queue.waitForMessagesAndGetAsString();
expect(batch?.items.map(item => item.localId)).toEqual(['id-a', 'id-b']);
expect(queue.size()).toBe(0);
queue.unshiftBatch(batch!);
expect(queue.pendingLocalIds()).toEqual(['id-a', 'id-b']);
const again = await queue.waitForMessagesAndGetAsString();
expect(again?.message).toBe('a\nb');
expect(again?.items.map(item => item.localId)).toEqual(['id-a', 'id-b']);
// One ACK per collection: the unshift itself fired none.
expect(consumed).toEqual([['id-a', 'id-b'], ['id-a', 'id-b']]);
});
it('unshiftBatch preserves internal provenance for non-isolated batches', async () => {
const queue = new MessageQueue2<string>(mode => mode);
const internal = { kind: 'control' } as const;
// A non-isolated batch that carries an internal item (the shape the
// launchers' requeue helpers hand back): the unshift branch must keep
// the provenance or hasPendingNonBridgeTurn miscounts the row.
queue.unshiftBatch({
mode: 'local',
isolate: false,
items: [{ message: 'ctrl', localId: 'id-c', internal }]
});
const again = await queue.waitForMessagesAndGetAsString();
expect(again?.items[0]?.internal).toEqual(internal);
});
it('should push and retrieve messages with same mode', async () => {
const queue = new MessageQueue2<string>(mode => mode);
@@ -136,16 +248,108 @@ describe('MessageQueue2', () => {
it('should handle abort signal with existing messages', async () => {
const queue = new MessageQueue2<string>(mode => mode);
const abortController = new AbortController();
// Add messages
queue.push('message1', 'local');
// Should return messages even with abort signal
const result = await queue.waitForMessagesAndGetAsString(abortController.signal);
expect(result).not.toBeNull();
expect(result?.message).toBe('message1');
});
it('does not collect or ACK pending messages when the signal is already aborted', async () => {
const queue = new MessageQueue2<string>(mode => mode);
const consumed: string[][] = [];
queue.onBatchConsumed = (ids) => { consumed.push([...ids]); };
queue.push('message1', 'local', 'id1');
queue.push('message2', 'local', 'id2');
const abortController = new AbortController();
abortController.abort();
const result = await queue.waitForMessagesAndGetAsString(abortController.signal);
expect(result).toBeNull();
expect(consumed).toEqual([]);
expect(queue.pendingLocalIds()).toEqual(['id1', 'id2']);
});
it.each(['pending', 'awakened'] as const)('preserves internal control identity across an aborted %s drain', async (state) => {
const queue = new MessageQueue2<string>(mode => mode);
const consumed: string[][] = [];
queue.onBatchConsumed = ids => { consumed.push([...ids]); };
const controller = new AbortController();
const waiting = state === 'awakened'
? queue.waitForMessagesAndGetAsString(controller.signal)
: undefined;
queue.pushIsolated('/auto on', 'remote', undefined, { internal: { kind: 'control' } });
queue.push('follow-up', 'remote', 'original-user');
controller.abort();
expect(await (waiting ?? queue.waitForMessagesAndGetAsString(controller.signal))).toBeNull();
expect(queue.size()).toBe(2);
expect(consumed).toEqual([]);
const control = await queue.waitForMessagesAndGetAsString(new AbortController().signal);
expect(control?.items).toEqual([{ message: '/auto on', localId: undefined, internal: { kind: 'control' } }]);
expect(control?.isolate).toBe(true);
expect(consumed).toEqual([]);
const user = await queue.waitForMessagesAndGetAsString();
expect(user?.items).toEqual([{ message: 'follow-up', localId: 'original-user', internal: undefined }]);
expect(consumed).toEqual([['original-user']]);
expect(queue.size()).toBe(0);
});
it('does not collect an idle-waited message that arrives while the signal is aborted; a fresh signal collects it exactly once', async () => {
const queue = new MessageQueue2<string>(mode => mode);
const consumed: string[][] = [];
queue.onBatchConsumed = (ids) => { consumed.push([...ids]); };
const abortController = new AbortController();
const pending = queue.waitForMessagesAndGetAsString(abortController.signal);
// Abort, then a message arrives during teardown — must NOT be collected.
abortController.abort();
queue.push('message1', 'local', 'id1');
const result = await pending;
expect(result).toBeNull();
expect(consumed).toEqual([]);
expect(queue.pendingLocalIds()).toEqual(['id1']);
// After teardown, a fresh (non-aborted) signal collects the same
// message exactly once.
const fresh = new AbortController();
const second = await queue.waitForMessagesAndGetAsString(fresh.signal);
expect(second?.message).toBe('message1');
expect(consumed).toEqual([['id1']]);
expect(queue.size()).toBe(0);
});
it('does not collect when the idle waiter wakes true and the signal aborts before the continuation', async () => {
const queue = new MessageQueue2<string>(mode => mode);
const consumed: string[][] = [];
queue.onBatchConsumed = (ids) => { consumed.push([...ids]); };
const abortController = new AbortController();
const pending = queue.waitForMessagesAndGetAsString(abortController.signal);
// Wake the waiter with a message, then synchronously abort so the
// post-await continuation must NOT collectBatch / ACK.
queue.push('message1', 'local', 'id1');
abortController.abort();
const result = await pending;
expect(result).toBeNull();
expect(consumed).toEqual([]);
expect(queue.pendingLocalIds()).toEqual(['id1']);
const fresh = new AbortController();
const second = await queue.waitForMessagesAndGetAsString(fresh.signal);
expect(second?.message).toBe('message1');
expect(consumed).toEqual([['id1']]);
expect(queue.size()).toBe(0);
});
it('should throw when pushing to closed queue', () => {
const queue = new MessageQueue2<string>(mode => mode);
queue.close();
+122 -5
View File
@@ -46,6 +46,14 @@ export type CollectedQueueItem = {
internal?: QueueItemInternal
};
export type CollectedQueueBatch<T> = {
message: string;
mode: T;
isolate: boolean;
hash: string;
items: CollectedQueueItem[];
};
/**
* A mode-aware message queue that stores messages with their modes.
* Returns consistent batches of messages with the same mode.
@@ -61,6 +69,9 @@ export class MessageQueue2<T> {
modeHasher: (mode: T) => string;
private readonly reservations = new Map<string, QueueReservation<T>>();
private readonly consumedReservations = new Set<string>();
/** localIds dequeued in a deferred-ACK window and not yet settled. */
private readonly inFlightLocalIds = new Set<string>();
private deferredAckDepth = 0;
private nextEnqueueOrder = 0;
private previousEnqueueOrder = -1;
@@ -247,7 +258,7 @@ export class MessageQueue2<T> {
/**
* Push a message to the beginning of the queue with a mode.
*/
unshift(message: string, mode: T, localId?: string): void {
unshift(message: string, mode: T, localId?: string, options?: QueueItemOptions): void {
if (this.closed) {
throw new Error('Cannot unshift to closed queue');
}
@@ -261,10 +272,14 @@ export class MessageQueue2<T> {
modeHash,
localId,
isolate: false,
internal: options?.internal,
enqueueOrder: this.previousEnqueueOrder--
};
Object.defineProperty(item, 'enqueueOrder', { value: item.enqueueOrder, enumerable: false, writable: true });
this.queue.unshift(item);
if (localId) {
this.inFlightLocalIds.delete(localId);
}
// Trigger message handler if set
if (this.onMessageHandler) {
@@ -308,6 +323,9 @@ export class MessageQueue2<T> {
};
Object.defineProperty(item, 'enqueueOrder', { value: item.enqueueOrder, enumerable: false, writable: true });
this.queue.unshift(item);
if (localId) {
this.inFlightLocalIds.delete(localId);
}
if (this.onMessageHandler) {
this.onMessageHandler(message, mode);
@@ -322,6 +340,25 @@ export class MessageQueue2<T> {
logger.debug(`[MessageQueue2] unshiftIsolated() completed. Queue size: ${this.queue.length}`);
}
/**
* Put a batch previously returned by
* {@link waitForMessagesAndGetAsString} back at the queue head, in its
* original order, with each item's localId and internal flag intact, so a
* retry stays connected to its hub row (collectBatch joins same-mode items
* into one string but still returns the per-item breakdown). Fires no
* consumed ACK: the re-collected batch is ACKed exactly like a fresh one.
*/
unshiftBatch(batch: { mode: T; isolate: boolean; items: CollectedQueueItem[] }): void {
for (let i = batch.items.length - 1; i >= 0; i -= 1) {
const item = batch.items[i]!;
if (batch.isolate) {
this.unshiftIsolated(item.message, batch.mode, item.localId, { internal: item.internal });
} else {
this.unshift(item.message, batch.mode, item.localId, { internal: item.internal });
}
}
}
/**
* True when a user/API turn is already waiting (queued or reserved).
* Only items with no `internal` provenance count: every internal kind —
@@ -368,6 +405,14 @@ export class MessageQueue2<T> {
this.queue.splice(idx, 1);
return true;
}
if (this.inFlightLocalIds.has(localId)) {
// Dequeued but not yet committed: the launcher owns the row inside
// the deferred-ACK window and may still commit it. A cancel can
// neither un-send it nor stamp it consumed — the hub keeps the row
// in-flight instead of deleting it (which would let a retry
// re-emit a message that is about to be delivered anyway).
return 'in-flight';
}
const reservation = this.reservations.get(localId);
if (!reservation) {
return this.consumedReservations.has(localId) ? 'consumed' : false;
@@ -564,6 +609,7 @@ export class MessageQueue2<T> {
reset(options?: { preserveDispatchingReservations?: boolean }): void {
logger.debug(`[MessageQueue2] reset() called. Clearing ${this.queue.length} messages`);
this.queue = [];
this.inFlightLocalIds.clear();
this.cancelReservations(options?.preserveDispatchingReservations === true);
this.closed = false;
@@ -619,6 +665,7 @@ export class MessageQueue2<T> {
close(): void {
logger.debug(`[MessageQueue2] close() called`);
this.closed = true;
this.inFlightLocalIds.clear();
this.cancelReservations();
// Notify any waiting caller
@@ -643,13 +690,70 @@ export class MessageQueue2<T> {
return this.queue.length;
}
/**
* Wait for and collect a batch without invoking {@link onBatchConsumed}
* immediately. Collected localIds stay marked in-flight until settled via
* {@link commitBatch}, {@link releaseBatch}, {@link unshiftBatch},
* {@link reset}, or {@link close}.
*/
async waitForDeferredBatch(abortSignal?: AbortSignal): Promise<CollectedQueueBatch<T> | null> {
this.deferredAckDepth += 1;
try {
const batch = await this.waitForMessagesAndGetAsString(abortSignal);
if (batch) {
this.beginBatch(batch);
}
return batch;
} finally {
this.deferredAckDepth -= 1;
}
}
/** Mark a dequeued batch's localIds as in-flight for cancel tracking. */
beginBatch(batch: Pick<CollectedQueueBatch<T>, 'items'>): void {
for (const item of batch.items) {
if (item.localId) {
this.inFlightLocalIds.add(item.localId);
}
}
}
/** Clear in-flight marks for a deferred batch and emit its hub ACK. */
commitBatch(batch: Pick<CollectedQueueBatch<T>, 'items'>): void {
const consumedLocalIds = this.clearInFlightBatch(batch);
if (consumedLocalIds.length > 0) {
this.onBatchConsumed?.(consumedLocalIds);
}
}
/** Clear in-flight marks for a deferred batch that is dropped without ACK. */
releaseBatch(batch: Pick<CollectedQueueBatch<T>, 'items'>): void {
this.clearInFlightBatch(batch);
}
private clearInFlightBatch(batch: Pick<CollectedQueueBatch<T>, 'items'>): string[] {
const localIds: string[] = [];
for (const item of batch.items) {
if (item.localId) {
this.inFlightLocalIds.delete(item.localId);
localIds.push(item.localId);
}
}
return localIds;
}
/**
* Wait for messages and return all messages with the same mode as a single string
* Returns { message: string, mode: T } or null if aborted/closed
*/
async waitForMessagesAndGetAsString(abortSignal?: AbortSignal): Promise<{ message: string, mode: T, isolate: boolean, hash: string, items: CollectedQueueItem[] } | null> {
// If we have messages, return them immediately
async waitForMessagesAndGetAsString(abortSignal?: AbortSignal): Promise<CollectedQueueBatch<T> | null> {
// If we have messages, return them immediately — but never collect for
// an aborted signal: collectBatch fires onBatchConsumed, so an aborted
// caller must neither ACK nor replay a pending batch.
if (this.queue.length > 0) {
if (abortSignal?.aborted) {
return null;
}
return this.collectBatch();
}
@@ -665,13 +769,20 @@ export class MessageQueue2<T> {
return null;
}
// Abort may have landed while we waited; do not collect (and ACK) a
// batch in that case — the caller re-loops and drains after the abort
// teardown settles.
if (abortSignal?.aborted) {
return null;
}
return this.collectBatch();
}
/**
* Collect a batch of messages with the same mode, respecting isolation requirements
*/
private collectBatch(): { message: string, mode: T, hash: string, isolate: boolean, items: CollectedQueueItem[] } | null {
private collectBatch(): CollectedQueueBatch<T> | null {
if (this.queue.length === 0) {
return null;
}
@@ -713,7 +824,13 @@ export class MessageQueue2<T> {
// Join all messages with newlines
const combinedMessage = sameModeMessages.join('\n');
if (consumedLocalIds.length > 0) {
if (this.deferredAckDepth > 0) {
// Dequeued inside a deferred-ACK window: cancelByLocalId answers
// 'in-flight' until commitBatch/releaseBatch/unshiftBatch/reset/close.
for (const id of consumedLocalIds) {
this.inFlightLocalIds.add(id);
}
} else if (consumedLocalIds.length > 0) {
this.onBatchConsumed?.(consumedLocalIds);
}