diff --git a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/GroupChatPage.module.css b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/GroupChatPage.module.css index 7e1fd2284c..0e2313fa34 100644 --- a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/GroupChatPage.module.css +++ b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/GroupChatPage.module.css @@ -837,6 +837,81 @@ color: var(--dsw-alias-state-error-primary); } +/* ==================== Room Stop Error Banner ==================== */ + +.stopErrorBar { + flex: none; + display: flex; + flex-direction: column; + padding: 8px 20px; + border-bottom: 0.5px solid var(--dsw-alias-border-l1); + background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 8%, var(--dsw-alias-bg-base)); +} + +.stopErrorItem { + max-width: var(--dsh-chat-content-width, 748px); + width: 100%; + margin: 0 auto; + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.stopErrorInfo { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + color: var(--dsw-alias-state-error-primary); + font-size: 12.5px; + line-height: 1.4; +} + +.stopErrorActions { + flex: none; + display: flex; + align-items: center; + gap: 6px; +} + +.stopErrorAction, +.stopErrorDismiss { + flex: none; + height: 26px; + padding: 0 10px; + border-radius: var(--dsw-radius-md, 8px); + font-size: 12px; + font-weight: 500; + cursor: pointer; +} + +.stopErrorAction { + border: 0.5px solid color-mix(in srgb, var(--dsw-alias-state-error-primary) 36%, transparent); + background: var(--dsw-alias-bg-base); + color: var(--dsw-alias-label-primary); +} + +.stopErrorAction:hover:not(:disabled) { + background: var(--dsw-alias-interactive-bg-hover); +} + +.stopErrorAction:disabled { + opacity: 0.55; + cursor: default; +} + +.stopErrorDismiss { + border: 0.5px solid transparent; + background: transparent; + color: var(--dsw-alias-label-secondary); +} + +.stopErrorDismiss:hover { + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-primary); +} + /* ==================== Needs You Banner ==================== */ .needsYouBar { diff --git a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/GroupChatPage.tsx b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/GroupChatPage.tsx index 5692d3235d..f16a25b888 100644 --- a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/GroupChatPage.tsx +++ b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/GroupChatPage.tsx @@ -24,7 +24,12 @@ import { GroupComposer, type GroupComposerSendPayload } from "./GroupComposer.ts import { GroupEditorModal } from "./GroupEditorModal.tsx"; import { MemberAvatar } from "./GroupAvatarStack.tsx"; import { GroupTimeline, type GroupOpenFileHandler } from "./GroupTimeline.tsx"; -import { GroupLiveObserver, type GroupLiveObserverTarget } from "./live-observer.ts"; +import { + GroupLiveObserver, + inspectSessionLatestTurn, + type GroupLiveObserverTarget, + type GroupLiveStopToken, +} from "./live-observer.ts"; import { GroupWidthControls } from "./GroupWidthControls.tsx"; import type { GroupStore } from "./store.ts"; import css from "./GroupChatPage.module.css"; @@ -121,6 +126,8 @@ export function GroupChatPage({ const [replyTarget, setReplyTarget] = useState(null); const [followingTail, setFollowingTail] = useState(true); const [stoppingMemberIds, setStoppingMemberIds] = useState>(() => new Set()); + const [stoppingRoomId, setStoppingRoomId] = useState(null); + const stopRoomAttemptSeqRef = useRef(0); const stoppingTimersRef = useRef>(new Map()); const stoppingThreadsRef = useRef>(new Map()); const stoppingRequestSeqRef = useRef>(new Map()); @@ -311,9 +318,18 @@ export function GroupChatPage({ const handleStopMember = sessions === undefined ? undefined - : (memberId: string, threadId: string): void => { + : ( + memberId: string, + threadId: string, + preCapturedToken?: GroupLiveStopToken | null, + expectedTurnKeyOverride?: string | null, + ): void => { const roomAtStart = room.roomId; - const stopGuard = liveObserver.getMemberStopToken(memberId, threadId); + const stopGuard = + preCapturedToken !== undefined + ? preCapturedToken + : liveObserver.getMemberStopToken(memberId, threadId); + const expectedTurnKey = stopGuard?.turnKey ?? expectedTurnKeyOverride ?? null; const reqSeq = (stoppingRequestSeqRef.current.get(memberId) ?? 0) + 1; stoppingRequestSeqRef.current.set(memberId, reqSeq); stoppingThreadsRef.current.set(memberId, threadId); @@ -330,7 +346,19 @@ export function GroupChatPage({ const result = await sessions.using( threadId as SessionId, { source: "groupLivePreview" }, - (ref) => ref.binding.session.cancel(), + (ref) => { + if (expectedTurnKey !== null) { + const latestTurn = inspectSessionLatestTurn(ref); + if ( + latestTurn === null || + latestTurn.closed || + latestTurn.turnKey !== expectedTurnKey + ) { + return { ok: false as const }; + } + } + return ref.binding.session.cancel(); + }, ); accepted = result.ok; } catch { @@ -347,7 +375,11 @@ export function GroupChatPage({ accepted && threadStillMatches ? liveObserver.suppressGrace( memberId, - stopGuard ?? { roomId: roomAtStart, threadId }, + stopGuard ?? { + roomId: roomAtStart, + threadId, + ...(expectedTurnKey !== null ? { turnKey: expectedTurnKey } : {}), + }, ) : false; if (accepted && threadStillMatches && suppressed) { @@ -378,21 +410,151 @@ export function GroupChatPage({ })(); }; + const handleRetryStopRoom = (): void => { + const targetRoomId = room.roomId; + const attemptSeq = ++stopRoomAttemptSeqRef.current; + setStoppingRoomId(targetRoomId); + void groupStore + .stopRoom(targetRoomId) + .catch(() => undefined) + .finally(() => { + if (stopRoomAttemptSeqRef.current === attemptSeq) { + setStoppingRoomId((prev) => (prev === targetRoomId ? null : prev)); + } + }); + }; + const handleStopAll = sessions === undefined ? undefined : (): void => { if (handleStopMember === undefined) return; + const roomAtStart = room.roomId; + const roomTitleAtStart = room.title; + const attemptSeq = ++stopRoomAttemptSeqRef.current; + // Capture each target's Turn identity synchronously at click time from liveObserver. + // Never probe asynchronously via `sessions.using()`, which could resolve after the + // click-time Turn ended and misidentify a newer Turn on the same Thread. + let skippedUnknownTurnCount = 0; + const targetsToCancel: Array<{ + readonly memberId: string; + readonly threadId: string; + readonly capturedTurnKey: string; + }> = []; for (const target of liveTargets) { - if (!stoppingMemberIds.has(target.member.memberId)) { - handleStopMember(target.member.memberId, target.member.threadId); + if (stoppingMemberIds.has(target.member.memberId)) continue; + const clickTurn = liveObserver.inspectMemberClickTurn( + target.member.memberId, + target.member.threadId, + ); + if (clickTurn.status === "open") { + targetsToCancel.push({ + memberId: target.member.memberId, + threadId: target.member.threadId, + capturedTurnKey: clickTurn.turnKey, + }); + } else if (clickTurn.status === "unknown") { + skippedUnknownTurnCount += 1; } } + setStoppingRoomId(roomAtStart); + if (targetsToCancel.length > 0) { + setStoppingMemberIds((prev) => { + const next = new Set(prev); + for (const target of targetsToCancel) next.add(target.memberId); + return next; + }); + } + // Wait for `codexhost/groups/stop` to settle before cancelling active turns so queued + // wakes cannot launch on `threadIdle` before the host pauses relays and clears wakes. + const stopRoomResultPromise = groupStore + .stopRoom(roomAtStart) + .then(() => ({ ok: true as const })) + .catch((error: unknown) => ({ + ok: false as const, + message: + error instanceof Error && error.message.trim().length > 0 + ? error.message.trim() + : String(error), + })); + void stopRoomResultPromise.then((stopOutcome) => { + if (stopRoomAttemptSeqRef.current === attemptSeq) { + setStoppingRoomId((prev) => (prev === roomAtStart ? null : prev)); + } + for (const target of targetsToCancel) { + if (mountedRoomIdRef.current === roomAtStart) { + const currentTarget = latestLiveTargetsRef.current.find( + (item) => item.member.memberId === target.memberId, + ); + const sameBinding = + currentTarget !== undefined && currentTarget.member.threadId === target.threadId; + // Check Turn identity directly (not slotGeneration) so switching away and back + // to the same room while the original Turn is still open still cancels it. + const currentToken = sameBinding + ? liveObserver.getMemberStopToken(target.memberId, target.threadId) + : null; + const turnReplaced = + currentToken !== null && + currentToken.turnKey !== null && + currentToken.turnKey !== target.capturedTurnKey; + if (!sameBinding || turnReplaced) { + setStoppingMemberIds((prev) => { + if (!prev.has(target.memberId)) return prev; + const next = new Set(prev); + next.delete(target.memberId); + return next; + }); + continue; + } + const graceGuard = + currentToken !== null && currentToken.turnKey === target.capturedTurnKey + ? currentToken + : null; + handleStopMember( + target.memberId, + target.threadId, + graceGuard, + target.capturedTurnKey, + ); + } else { + void sessions + .using(target.threadId as SessionId, { source: "groupLivePreview" }, (ref) => { + const latestTurn = inspectSessionLatestTurn(ref); + if ( + latestTurn === null || + latestTurn.closed || + latestTurn.turnKey !== target.capturedTurnKey + ) { + return { ok: false as const }; + } + return ref.binding.session.cancel(); + }) + .catch(() => undefined); + } + } + const notices: string[] = []; + if (!stopOutcome.ok && mountedRoomIdRef.current !== roomAtStart) { + notices.push( + t("stopRoom.failedNotice", { + title: roomTitleAtStart, + message: stopOutcome.message, + }), + ); + } + if (skippedUnknownTurnCount > 0) { + notices.push(t("stopRoom.unknownTurnSkipped")); + } + if (notices.length > 0) { + groupStore.showNotice(notices.join(" ")); + } + }); }; + const stopRoomError = state.stopErrorByRoom[room.roomId] ?? null; const allTargetsStopping = - liveTargets.length > 0 && - liveTargets.every((target) => stoppingMemberIds.has(target.member.memberId)); + stoppingRoomId === room.roomId || + (liveTargets.length > 0 && + liveTargets.every((target) => stoppingMemberIds.has(target.member.memberId))); const cwdOfThread = (threadId: string): string | undefined => sessionList.byId[threadId as SessionId]?.cwd; @@ -425,6 +587,35 @@ export function GroupChatPage({ t={t} /> + {stopRoomError !== null && ( +
+
+
+ + {t("stopRoom.failed", { message: stopRoomError })} +
+
+ + +
+
+
+ )} + {topNeedsYouItems.length > 0 && (
{topNeedsYouItems.map((item) => ( diff --git a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/api.ts b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/api.ts index f34cb86588..2d62d2ae81 100644 --- a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/api.ts +++ b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/api.ts @@ -15,6 +15,7 @@ import { GROUPS_READ_MESSAGES_METHOD, GROUPS_REBIND_MEMBER_METHOD, GROUPS_REMOVE_MEMBER_METHOD, + GROUPS_STOP_METHOD, GROUPS_UPDATE_MEMBER_METHOD, GROUPS_UPDATE_MEMORY_METHOD, GROUPS_UPDATE_METHOD, @@ -41,6 +42,8 @@ import { type GroupsRebindMemberResult, type GroupsRemoveMemberParams, type GroupsRemoveMemberResult, + type GroupsStopParams, + type GroupsStopResult, type GroupsUpdateMemberParams, type GroupsUpdateMemberResult, type GroupsUpdateMemoryParams, @@ -272,6 +275,9 @@ export const groupsApi = { update(params: GroupsUpdateParams): Promise { return groupCall(GROUPS_UPDATE_METHOD, params); }, + stop(params: GroupsStopParams): Promise { + return groupCall(GROUPS_STOP_METHOD, params, READ_CALL_OPTIONS); + }, delete(params: GroupsDeleteParams): Promise { return groupCall(GROUPS_DELETE_METHOD, params); }, diff --git a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/live-observer.ts b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/live-observer.ts index 1e914b3cec..44dd64b8dd 100644 --- a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/live-observer.ts +++ b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/live-observer.ts @@ -62,6 +62,11 @@ export interface GroupLiveStopGuard { readonly turnEpoch?: number | undefined; } +export type GroupLiveClickTurnStatus = + | { readonly status: "open"; readonly turnKey: string } + | { readonly status: "closed" } + | { readonly status: "unknown" }; + export interface GroupLiveStopToken { readonly roomId: string; readonly memberId: string; @@ -193,6 +198,22 @@ function latestSeqOf(messages: readonly GroupMessage[]): number { return max; } +export interface SessionLatestTurnInfo { + readonly turnKey: string; + readonly closed: boolean; +} + +/** Read the latest turn identity and completion status from a live SessionReference. */ +export function inspectSessionLatestTurn( + ref: SessionReference | null, +): SessionLatestTurnInfo | null { + const entries = readEventEntries(ref); + if (entries === null) return null; + const latest = inspectLatestTurn(entries); + if (latest === null) return null; + return { turnKey: latest.turnKey, closed: latest.closed }; +} + function readEventEntries(ref: SessionReference | null): readonly SessionEventLikeEntry[] | null { if (ref === null) return null; try { @@ -364,7 +385,9 @@ export class GroupLiveObserver { slot.suppressGrace = false; slot.hasSeenOpenTurn = false; slot.lastOpenActivity = null; - slot.turnEpoch += 1; + if (turnInfo.closed) { + slot.turnEpoch += 1; + } slot.settledTurnKey = turnInfo.turnKey; slot.settledHidden = slot.pendingKind === undefined; messageSettledCurrentTurn = true; @@ -473,6 +496,51 @@ export class GroupLiveObserver { } } + /** + * Synchronously inspect the member's click-time Turn identity from the currently retained + * event source (or any already-live Session mounted elsewhere in the client) without creating + * a new scope or performing async session loads (preventing a later Turn from being + * misattributed to the click). + */ + inspectMemberClickTurn(memberId: string, threadId: string): GroupLiveClickTurnStatus { + if (this.disposed || this.roomId === null) return { status: "unknown" }; + const slot = this.slots.get(memberId); + if (slot !== undefined && slot.threadId === threadId) { + const latestTurn = inspectSessionLatestTurn(slot.ref); + if (latestTurn !== null) { + return latestTurn.closed + ? { status: "closed" } + : { status: "open", turnKey: latestTurn.turnKey }; + } + if (slot.activity.turnClosed) return { status: "closed" }; + if (slot.lastObservedTurnKey !== null) { + return { status: "open", turnKey: slot.lastObservedTurnKey }; + } + } + const sessions = this.sessions; + if (sessions !== undefined && typeof sessions.retainInfo === "function") { + const retainedCount = sessions.retainInfo(threadId as SessionId).getSnapshot().referenceCount; + if (retainedCount > 0) { + let tempRef: SessionReference | null = null; + try { + tempRef = sessions.retain(threadId as SessionId, { source: "groupLivePreview" }); + void tempRef.ready.catch(() => undefined); + const latestTurn = inspectSessionLatestTurn(tempRef); + if (latestTurn !== null) { + return latestTurn.closed + ? { status: "closed" } + : { status: "open", turnKey: latestTurn.turnKey }; + } + } catch { + /* fall through to unknown */ + } finally { + tempRef?.release(); + } + } + } + return { status: "unknown" }; + } + /** Capture the current room/thread/slot/turn identity before issuing an async cancel(). */ getMemberStopToken(memberId: string, threadId: string): GroupLiveStopToken | null { if (this.disposed || this.roomId === null) return null; @@ -488,6 +556,27 @@ export class GroupLiveObserver { }; } + /** + * Check whether a previously captured stop token still matches the member's active turn. + * When clicked before initial history arrived (`turnKey === null`), loading that first open + * turn (`turnEpoch <= 1` and not closed) is treated as initial observation rather than replacement. + */ + isMemberStopTokenCurrent(token: GroupLiveStopToken | null): boolean { + if (this.disposed || token === null || this.roomId !== token.roomId) return false; + const slot = this.slots.get(token.memberId); + if (slot === undefined || !slot.activeTarget) return false; + if (slot.threadId !== token.threadId) return false; + if (slot.generation !== token.slotGeneration) return false; + const latestTurn = inspectSessionLatestTurn(slot.ref); + if (slot.activity.turnClosed || latestTurn?.closed === true) return false; + if (token.turnKey === null) { + return slot.turnEpoch <= 1; + } + if (slot.turnEpoch !== token.turnEpoch) return false; + if (slot.lastObservedTurnKey !== token.turnKey) return false; + return true; + } + /** Bypass post-turn streaming grace when the user explicitly stops a member Turn. */ suppressGrace(memberId: string, guard?: GroupLiveStopGuard): boolean { if (this.disposed) return false; diff --git a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/locales.ts b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/locales.ts index e7d98fb848..688f35f370 100644 --- a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/locales.ts +++ b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/locales.ts @@ -229,6 +229,14 @@ export const en = { "composer.stop": "Stop", "composer.stopAll": "Stop all ({count})", "composer.stopping": "Stopping…", + "stopRoom.failed": + "Couldn’t pause group relay or clear queued wakes ({message}). Active members were still asked to stop, but queued teammates may resume until stopped.", + "stopRoom.failedNotice": "Couldn’t stop group “{title}”: {message}", + "stopRoom.retry": "Retry stop", + "stopRoom.retrying": "Stopping…", + "stopRoom.dismiss": "Dismiss", + "stopRoom.unknownTurnSkipped": + "Some running members couldn’t be matched to an active Turn and were skipped to avoid aborting newer work. Stop them individually if still running.", "composer.attachImage": "Upload image", "composer.attach": "Upload file", "composer.uploading": "Uploading…", @@ -594,6 +602,14 @@ export const zh: Record = { "composer.stop": "停止", "composer.stopAll": "停止全部({count})", "composer.stopping": "正在停止…", + "stopRoom.failed": + "未能暂停群聊自动接力并清空排队唤醒({message})。已尝试停止当前运行中的成员,但排队成员仍可能继续启动,请重试停止。", + "stopRoom.failedNotice": "停止群聊「{title}」失败:{message}", + "stopRoom.retry": "重试停止", + "stopRoom.retrying": "正在停止…", + "stopRoom.dismiss": "关闭", + "stopRoom.unknownTurnSkipped": + "部分运行中的成员未能确认当前 Turn 身份,已跳过自动中止以避免误停较新任务;如仍在运行,请在对应成员卡片单独点击停止。", "composer.attachImage": "上传图片", "composer.attach": "上传文件", "composer.uploading": "上传中…", diff --git a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/store.ts b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/store.ts index ff042d9e9d..9c6ad26b68 100644 --- a/apps/web-ui/packages/client/ui-codexhost/src/client/groups/store.ts +++ b/apps/web-ui/packages/client/ui-codexhost/src/client/groups/store.ts @@ -25,7 +25,7 @@ import type { HarnessId, ThreadHandoffReboundGroup, } from "@codexhost/shared-contracts"; -import { groupsApi } from "./api.ts"; +import { GroupRequestError, groupsApi } from "./api.ts"; import { deriveSidebarGroupRooms, roomTimestampMs } from "./derive.ts"; import { createLatestLeaderQueue, @@ -104,6 +104,7 @@ export interface GroupStoreState { readonly loadingRoomId: string | null; readonly loadingOlderRoomId: string | null; readonly roomError: string | null; + readonly stopErrorByRoom: Readonly>; /** Optimistic per-room leader choice while a save is in-flight or queued (`null` = off). */ readonly pendingLeaderByRoom: Readonly>; /** Latest settled leader-save error per room, retained until a new selection or retry clears it. */ @@ -198,6 +199,7 @@ export class GroupStore { loadingRoomId: null, loadingOlderRoomId: null, roomError: null, + stopErrorByRoom: {}, pendingLeaderByRoom: {}, leaderErrorByRoom: {}, returnToGroupRoomId: null, @@ -487,6 +489,60 @@ export class GroupStore { return room; } + clearStopError(roomId: string): void { + const current = this.store.getSnapshot().stopErrorByRoom; + if (!(roomId in current)) return; + this.store.update((draft) => { + const { [roomId]: _removed, ...rest } = draft.stopErrorByRoom; + draft.stopErrorByRoom = rest; + }); + } + + private setStopError(roomId: string, message: string): void { + this.store.update((draft) => { + draft.stopErrorByRoom = { + ...draft.stopErrorByRoom, + [roomId]: message, + }; + }); + } + + async stopRoom(roomId: string): Promise { + try { + let room: GroupRoom; + try { + const result = await groupsApi.stop({ roomId }); + room = result.room; + this.upsertRoom(room); + } catch (error) { + const unsupported = + (error instanceof GroupRequestError && + (error.code === "rpc/method-not-found" || + error.code === "gateway/not-found" || + error.code === "host/method-unavailable" || + (error.code === "http" && /^HTTP (?:404|405|501)\b/u.test(error.message)) || + /not available|not found|unknown group room method|no handler for/iu.test( + error.message, + ))) || + (error instanceof Error && + /not available|not found|unknown group room method|no handler for/iu.test( + error.message, + )); + if (!unsupported) throw error; + room = await this.updateRoom({ roomId, relayPaused: true }); + } + this.clearStopError(roomId); + return room; + } catch (error) { + const message = + error instanceof Error && error.message.trim().length > 0 + ? error.message.trim() + : String(error); + this.setStopError(roomId, message); + throw error; + } + } + /** * Queue a per-room leader-mode update on the store so ordering and retained failures survive * switching rooms or unmounting/remounting the group chat page. @@ -1071,8 +1127,10 @@ export class GroupStore { if (draft.deleteRoomId === roomId) draft.deleteRoomId = null; const { [roomId]: _removedMsgs, ...restMsgs } = draft.messagesByRoom; const { [roomId]: _removedMore, ...restMore } = draft.hasMoreByRoom; + const { [roomId]: _removedStopError, ...restStopError } = draft.stopErrorByRoom; draft.messagesByRoom = restMsgs; draft.hasMoreByRoom = restMore; + draft.stopErrorByRoom = restStopError; }); if (removedReadEntry) writePersistedLastReadSeq(restLastRead); this.scrollStateByRoom.delete(roomId); diff --git a/apps/web-ui/packages/client/ui-codexhost/test/group-live-activity.test.ts b/apps/web-ui/packages/client/ui-codexhost/test/group-live-activity.test.ts index 96c3e11a08..5fa086032f 100644 --- a/apps/web-ui/packages/client/ui-codexhost/test/group-live-activity.test.ts +++ b/apps/web-ui/packages/client/ui-codexhost/test/group-live-activity.test.ts @@ -23,7 +23,7 @@ import { formatLiveActivityPhrase, formatWorkDuration, } from "../src/client/groups/live-activity.ts"; -import { GroupLiveObserver } from "../src/client/groups/live-observer.ts"; +import { GroupLiveObserver, inspectSessionLatestTurn } from "../src/client/groups/live-observer.ts"; import { en as groupsEn, zh as groupsZh, @@ -481,6 +481,13 @@ describe("GroupLiveObserver", () => { [Symbol.dispose]: () => {}, }; }, + retainInfo: (id: SessionId) => ({ + getSnapshot: () => ({ + referenceCount: retained.get(String(id)) ?? 0, + retainedBy: {}, + }), + subscribe: () => () => {}, + }), } as unknown as ISessions; return { sessions, sources, retained, retainCalls, releaseCalls }; @@ -1108,4 +1115,206 @@ describe("GroupLiveObserver", () => { vi.useRealTimers(); } }); + + it("detects stale stop tokens when a turn ends or is replaced before async cancel runs", async () => { + const fake = createFakeSessions(); + const observer = new GroupLiveObserver(fake.sessions, { + graceMs: 2_500, + throttleMs: 0, + now: () => 95_000, + }); + const alice = makeMember("m-alice", "t-alice", "Alice"); + + observer.sync({ + active: true, + roomId: "room-1", + targets: [{ member: alice, status: "running" }], + messages: [], + }); + const source = fake.sources.get("t-alice")!; + source.append(durable("turn/start", { turn: 1 }, 95_100)); + const token = observer.getMemberStopToken("m-alice", "t-alice"); + expect(token?.turnKey).toMatch(/^\d+:1$/); + expect(observer.isMemberStopTokenCurrent(token)).toBe(true); + + // While turn 1 is open, inspectSessionLatestTurn matches token.turnKey and closed === false. + const ref = fake.sessions.retain("t-alice" as SessionId, { source: "groupLivePreview" }); + try { + expect(inspectSessionLatestTurn(ref)).toEqual({ turnKey: token!.turnKey, closed: false }); + + // Turn 1 ends and Turn 2 starts on the same shared thread (e.g. from another room). + source.append(durable("turn/end", { turn: 1, reason: "completed" }, 95_200)); + expect(inspectSessionLatestTurn(ref)).toEqual({ turnKey: token!.turnKey, closed: true }); + source.append(durable("turn/start", { turn: 2 }, 95_300)); + expect(observer.isMemberStopTokenCurrent(token)).toBe(false); + const latest = inspectSessionLatestTurn(ref); + expect(latest?.turnKey).not.toBe(token?.turnKey); + expect(latest?.closed).toBe(false); + } finally { + ref.release(); + } + + observer.dispose(); + }); + + it("treats initial open-turn observation as current for pre-history stop tokens until turn replacement", () => { + const fake = createFakeSessions(); + const observer = new GroupLiveObserver(fake.sessions, { + graceMs: 2_500, + throttleMs: 0, + now: () => 96_000, + }); + const alice = makeMember("m-alice", "t-alice", "Alice"); + + // User clicks Stop All before initial history arrives -> token has turnKey: null, turnEpoch: 0. + observer.sync({ + active: true, + roomId: "room-1", + targets: [{ member: alice, status: "running" }], + messages: [], + }); + const preHistoryToken = observer.getMemberStopToken("m-alice", "t-alice"); + expect(preHistoryToken?.turnKey).toBeNull(); + expect(observer.isMemberStopTokenCurrent(preHistoryToken)).toBe(true); + + // Same open turn's initial history arrives while stopRoom is in flight -> still current! + const source = fake.sources.get("t-alice")!; + source.append(durable("turn/start", { turn: 1 }, 96_100)); + expect(observer.isMemberStopTokenCurrent(preHistoryToken)).toBe(true); + + // Re-acquiring the consistent observer token captures the matching turnEpoch (1) so suppressGrace succeeds. + const refreshedToken = observer.getMemberStopToken("m-alice", "t-alice"); + expect(refreshedToken?.turnKey).toMatch(/^\d+:1$/); + expect(refreshedToken?.turnEpoch).toBe(1); + expect(observer.suppressGrace("m-alice", refreshedToken!)).toBe(true); + + // Once that turn ends (or a second turn starts), preHistoryToken is no longer current. + source.append(durable("turn/end", { turn: 1, reason: "completed" }, 96_200)); + expect(observer.isMemberStopTokenCurrent(preHistoryToken)).toBe(false); + source.append(durable("turn/start", { turn: 2 }, 96_300)); + expect(observer.isMemberStopTokenCurrent(preHistoryToken)).toBe(false); + + observer.dispose(); + }); + + it("keeps stop token current when a CLI group message settles the preview of the same still-open turn", () => { + const fake = createFakeSessions(); + const observer = new GroupLiveObserver(fake.sessions, { + graceMs: 2_500, + throttleMs: 0, + now: () => 97_000, + }); + const alice = makeMember("m-alice", "t-alice", "Alice"); + const target = { member: alice, status: "running" as const }; + + observer.sync({ active: true, roomId: "room-1", targets: [target], messages: [] }); + const source = fake.sources.get("t-alice")!; + source.append(durable("turn/start", { turn: 1 }, 97_100)); + source.append(liveChunk({ type: "text-delta", index: 0, text: "Working on task…" })); + + const stopToken = observer.getMemberStopToken("m-alice", "t-alice"); + expect(stopToken?.turnKey).toMatch(/^\d+:1$/); + expect(observer.isMemberStopTokenCurrent(stopToken)).toBe(true); + + // While stopRoom is in flight, the same open turn posts a CLI message that hides the duplicate preview. + const cliMsg: GroupMessage = { + ...makeAgentMessage("m-alice", 5, "Progress update via CLI"), + createdAt: new Date(97_200).toISOString(), + }; + observer.sync({ active: true, roomId: "room-1", targets: [target], messages: [cliMsg] }); + expect(observer.getSnapshot().entries).toHaveLength(0); + + // Turn 1 is still open -> stopToken must remain current and suppressGrace must still match! + expect(observer.isMemberStopTokenCurrent(stopToken)).toBe(true); + expect(observer.suppressGrace("m-alice", stopToken!)).toBe(true); + + // Once Turn 1 actually ends and Turn 2 starts, the old token becomes stale. + source.append(durable("turn/end", { turn: 1, reason: "completed" }, 97_300)); + expect(observer.isMemberStopTokenCurrent(stopToken)).toBe(false); + source.append(durable("turn/start", { turn: 2 }, 97_400)); + expect(observer.isMemberStopTokenCurrent(stopToken)).toBe(false); + + observer.dispose(); + }); + + it("synchronously classifies click-time member turns as open, closed, or unknown without async probing", () => { + const fake = createFakeSessions(); + const observer = new GroupLiveObserver(fake.sessions, { + maxRetains: 1, + graceMs: 2_500, + throttleMs: 0, + now: () => 98_000, + }); + const alice = makeMember("m-alice", "t-alice", "Alice"); + const bob = makeMember("m-bob", "t-bob", "Bob"); + + observer.sync({ + active: true, + roomId: "room-1", + targets: [ + { member: alice, status: "running" }, + { member: bob, status: "running" }, + ], + messages: [], + }); + + // Before history arrives (Alice) and when unretained past maxRetains (Bob), both report unknown, + // and checking unmounted Bob must NOT create a new retain. + expect(observer.inspectMemberClickTurn("m-alice", "t-alice")).toEqual({ status: "unknown" }); + const retainsBeforeBob = fake.retainCalls.filter((c) => c.threadId === "t-bob").length; + expect(observer.inspectMemberClickTurn("m-bob", "t-bob")).toEqual({ status: "unknown" }); + expect(fake.retainCalls.filter((c) => c.threadId === "t-bob").length).toBe(retainsBeforeBob); + + // If Bob is already retained elsewhere in the client (referenceCount > 0) despite exceeding + // maxRetains, inspectMemberClickTurn synchronously borrows and releases without leaking refs. + const externalBobRef = fake.sessions.retain("t-bob" as SessionId, { + source: "groupLivePreview", + }); + const bobSource = fake.sources.get("t-bob")!; + bobSource.append(durable("turn/start", { turn: 7 }, 98_050)); + expect(observer.inspectMemberClickTurn("m-bob", "t-bob")).toEqual({ + status: "open", + turnKey: expect.stringMatching(/^\d+:7$/), + }); + expect(fake.retained.get("t-bob")).toBe(1); + bobSource.append(durable("turn/end", { turn: 7, reason: "completed" }, 98_060)); + expect(observer.inspectMemberClickTurn("m-bob", "t-bob")).toEqual({ status: "closed" }); + expect(fake.retained.get("t-bob")).toBe(1); + externalBobRef.release(); + expect(fake.retained.get("t-bob")).toBeUndefined(); + + // Once Alice's open turn is observed, inspectMemberClickTurn returns open with its turnKey. + const aliceSource = fake.sources.get("t-alice")!; + aliceSource.append(durable("turn/start", { turn: 1 }, 98_100)); + const open = observer.inspectMemberClickTurn("m-alice", "t-alice"); + expect(open).toEqual({ status: "open", turnKey: expect.stringMatching(/^\d+:1$/) }); + + // When Alice's turn closes, inspectMemberClickTurn reports closed (not unknown). + aliceSource.append(durable("turn/end", { turn: 1, reason: "completed" }, 98_200)); + expect(observer.inspectMemberClickTurn("m-alice", "t-alice")).toEqual({ status: "closed" }); + + // Switching away and back rebuilds the slot generation, but suppressGrace guarded by turnKey still works. + aliceSource.append(durable("turn/start", { turn: 2 }, 98_300)); + aliceSource.append(liveChunk({ type: "text-delta", index: 0, text: "Turn 2 streaming" })); + const openTurn2 = observer.inspectMemberClickTurn("m-alice", "t-alice"); + expect(openTurn2.status).toBe("open"); + observer.sync({ active: true, roomId: "room-2", targets: [], messages: [] }); + observer.sync({ + active: true, + roomId: "room-1", + targets: [{ member: alice, status: "running" }], + messages: [], + }); + if (openTurn2.status === "open") { + expect( + observer.suppressGrace("m-alice", { + roomId: "room-1", + threadId: "t-alice", + turnKey: openTurn2.turnKey, + }), + ).toBe(true); + } + + observer.dispose(); + }); }); diff --git a/apps/web-ui/packages/client/ui-codexhost/test/group-sidebar.test.ts b/apps/web-ui/packages/client/ui-codexhost/test/group-sidebar.test.ts index 333ec3f623..5ebd052a55 100644 --- a/apps/web-ui/packages/client/ui-codexhost/test/group-sidebar.test.ts +++ b/apps/web-ui/packages/client/ui-codexhost/test/group-sidebar.test.ts @@ -1051,6 +1051,102 @@ describe("groups mobile visibility, timeout, recovery, and remote failures", () ); }); + it("stops a room via codexhost/groups/stop and falls back to relayPaused=true on legacy hosts", async () => { + const baseRoom = makeRoom("room-stop-1", "Stop Test", [{ memberId: "m-1", threadId: "t-1" }], { + relayPaused: false, + }); + const makeStore = () => + new GroupStore({ + selectGroupPanel: () => {}, + closeGroupPanelIfActive: () => {}, + openNativeThread: () => {}, + isGroupPanelActive: () => true, + markMemberSessionsRead: () => {}, + }); + + const calls: Array<{ method: string; args: Record }> = []; + setGroupRpcTransport(async (method: string, args: Record) => { + calls.push({ method, args }); + if (method === "codexhost/groups/stop") { + return { + room: { ...baseRoom, relayPaused: true }, + clearedPendingMemberIds: ["m-1"], + } as T; + } + throw new Error(`unexpected method ${method}`); + }); + const store = makeStore(); + const stopped = await store.stopRoom(baseRoom.roomId); + expect(stopped.relayPaused).toBe(true); + expect(store.store.getSnapshot().rooms[0]?.relayPaused).toBe(true); + expect(calls).toEqual([{ method: "codexhost/groups/stop", args: { roomId: baseRoom.roomId } }]); + + // Legacy host without codexhost/groups/stop falls back to codexhost/groups/update { relayPaused: true }. + const fallbackCalls: Array<{ method: string; args: Record }> = []; + setGroupRpcTransport(async (method: string, args: Record) => { + fallbackCalls.push({ method, args }); + if (method === "codexhost/groups/stop") { + throw new GroupRequestError("Client method is not available", "rpc/method-not-found"); + } + if (method === "codexhost/groups/update") { + return { room: { ...baseRoom, relayPaused: true } } as T; + } + throw new Error(`unexpected method ${method}`); + }); + const legacyStore = makeStore(); + const fallbackRoom = await legacyStore.stopRoom(baseRoom.roomId); + expect(fallbackRoom.relayPaused).toBe(true); + expect(fallbackCalls).toEqual([ + { method: "codexhost/groups/stop", args: { roomId: baseRoom.roomId } }, + { method: "codexhost/groups/update", args: { roomId: baseRoom.roomId, relayPaused: true } }, + ]); + + // Legacy v0.35.1 gateway/not-found envelope also falls back to relayPaused: true. + const gatewayCalls: string[] = []; + setGroupRpcTransport(async (method: string) => { + gatewayCalls.push(method); + if (method === "codexhost/groups/stop") { + throw new GroupRequestError( + "codexhost: no handler for codexhost/groups/stop", + "gateway/not-found", + ); + } + if (method === "codexhost/groups/update") { + return { room: { ...baseRoom, relayPaused: true } } as T; + } + throw new Error(`unexpected method ${method}`); + }); + const gatewayStore = makeStore(); + const gatewayStopped = await gatewayStore.stopRoom(baseRoom.roomId); + expect(gatewayStopped.relayPaused).toBe(true); + expect(gatewayCalls).toEqual(["codexhost/groups/stop", "codexhost/groups/update"]); + expect(gatewayStore.store.getSnapshot().stopErrorByRoom[baseRoom.roomId]).toBeUndefined(); + + // Real stop failure (e.g. HTTP 500 or remote offline) does NOT fall back, records stopErrorByRoom, + // and clears once a subsequent retry succeeds. + let shouldFail = true; + const retryCalls: string[] = []; + setGroupRpcTransport(async (method: string) => { + retryCalls.push(method); + if (method === "codexhost/groups/stop") { + if (shouldFail) throw new GroupRequestError("HTTP 500", "http"); + return { + room: { ...baseRoom, relayPaused: true }, + clearedPendingMemberIds: [], + } as T; + } + throw new Error(`unexpected method ${method}`); + }); + const failingStore = makeStore(); + await expect(failingStore.stopRoom(baseRoom.roomId)).rejects.toThrow("HTTP 500"); + expect(retryCalls).toEqual(["codexhost/groups/stop"]); + expect(failingStore.store.getSnapshot().stopErrorByRoom[baseRoom.roomId]).toBe("HTTP 500"); + + shouldFail = false; + await failingStore.stopRoom(baseRoom.roomId); + expect(failingStore.store.getSnapshot().stopErrorByRoom[baseRoom.roomId]).toBeUndefined(); + }); + it("gates leader mode controls by local vs remote capability and keeps EN/ZH leader locales in sync", () => { vi.stubGlobal("document", { body: {} }); expect(canConfigureGroupLeaderMode({ remote: undefined })).toBe(true); diff --git a/docs/architecture/multi-harness-group-chat.md b/docs/architecture/multi-harness-group-chat.md index 3f12d09b05..87f3eb210f 100644 --- a/docs/architecture/multi-harness-group-chat.md +++ b/docs/architecture/multi-harness-group-chat.md @@ -13,9 +13,10 @@ Multi-Harness Group Chat lets users bring multiple independent native Threads— - **Private by default**: A member's prior 1:1 conversation history, internal thinking, and raw tool traces never leak into the room timeline or into other members' contexts. Private 1:1 Turns sent directly in a member's native Thread stay off the group timeline. - **Zero-token idle + cursor delta delivery**: Unmentioned members are never awakened. When awakened, Host selects unread public messages from other senders (`seq > lastDeliveredSeq`, `senderThreadId !== member.threadId`) and packs them into a single `` `user` Turn payload within a `16 KiB` (`16_384` UTF-8 bytes) budget. -- **Omission index & on-demand CLI readback**: When unread public history exceeds `16 KiB` (including when an existing Thread joins with `includeRecentHistory: true`), older messages are omitted with a CDATA index pointing to `"$CODEXHOST_CLI_PATH" group read --from --to --format text`. -- **Dynamic roster versioning**: A compact `` (`name`, optional `note`, `leader="true"` when designated as leader, and `muted="true"` when muted) is included only on a member's first wake or when `room.rosterVersion` changes (member added, removed, muted, renamed, rebound, note updated, or leader changed/cleared). First wake also states the `@Name` parallel vs. ordered-step rule, leader/teammate collaboration rules when Leader Mode is active (and emits an explicit `` notice via `leaderClearedRosterVersion` when a room returns to open peer-to-peer mode), `` awareness, `[[NO_REPLY]]` silence protocol, and shared room memory CLI. -- **Activity awareness & silent turns (`[[NO_REPLY]]`)**: Each wake envelope includes an optional `busy: @Name (working|queued), ...` block listing other busy teammates (automatically omitted if a near-full roster would exceed the `16 KiB` context budget) so agents avoid redundant `@mention` wakeups while preserving explicit handoffs via Busy-turn coalescing. When a woken member has no substantive reply or action to take, returning only `[[NO_REPLY]]` suppresses posting to the public timeline while still advancing its delivery cursors. +- **Omission index & per-message `4 KiB` truncation (`GROUP_SINGLE_MESSAGE_MAX_BYTES`)**: Each individual unread message is capped at `4 KiB` (`4_096` UTF-8 bytes) before packing, with oversized messages truncated and annotated with a targeted `"$CODEXHOST_CLI_PATH" group read --from --to --format text` pull-back hint (preserving attachment lines and switching the pull-back hint to `--format json` when the truncated message includes attachments). When combined unread public history still exceeds `16 KiB` (including when an existing Thread joins with `includeRecentHistory: true`), older messages are omitted with a CDATA index pointing to `"$CODEXHOST_CLI_PATH" group read --from --to --format text`, and even a tight single-message fallback retains the targeted `--from --to ` hint whenever budget permits. +- **Dynamic roster versioning**: A compact `` (`name`, optional `note`, `leader="true"` when designated as leader, and `muted="true"` when muted) is included only on a member's first wake or when `room.rosterVersion` changes (member added, removed, muted, renamed, rebound, note updated, or leader changed/cleared). First wake also states the `@Name` parallel vs. ordered-step rule (plain names without `@` when quoting, thanking, or naming later teammates), leader/teammate collaboration rules when Leader Mode is active (and emits an explicit `` notice via `leaderClearedRosterVersion` when a room returns to open peer-to-peer mode), `` awareness, `[[NO_REPLY]]` silence protocol, concise reply guidance, and shared room memory CLI. +- **Activity awareness, de-`@` envelope & silent directives (`[[NO_REPLY]]`)**: To avoid echoing `@Name` tokens back into prompts where models might inadvertently mirror them, `` and `` omit leading `@` prefixes. Each wake envelope includes an optional `busy: Name (working|blocked|queued), ...` block listing other active, blocked (awaiting human approval or question response), or queued teammates (automatically omitted if a near-full roster would exceed the `16 KiB` context budget). Agent-to-agent auto-relays targeting `blocked` threads are suppressed automatically (explicit human `@mentions` still route normally). When a woken member has no substantive reply or action to take, returning only `[[NO_REPLY]]` (`isGroupNoReply`) suppresses posting while advancing delivery cursors; including a standalone `[[NO_REPLY]]` directive in prose outside Markdown code (`hasGroupNoReplyDirective`) publishes the note without triggering downstream agent relays. +- **Zero-unread skip, superseded busy-wake hint & same-turn CLI dedup**: Before starting a queued agent wake, Host checks whether the triggering message was already delivered or whether zero unread messages from other senders remain (skipping the wake unless first-wake/post-compaction metadata sync is required). If all remaining unread messages predate the member's own latest reply, Host injects a `` prompting `[[NO_REPLY]]` if already covered. Within a single active group Turn, CLI posts via `codexhost group post` are tracked per `(roomId, memberId)` on the flight so duplicate final Turn completions are deduplicated and teammates already awakened via CLI are not re-woken by the Turn wrap-up. - **Shared room memory & post-compaction recovery**: Each room maintains an optional shared Markdown memory document (`.memory.md`, default `4 KiB` UTF-8, configurable per room in `1–256 KiB` via `memoryMaxBytes`, versioned by `room.memoryVersion` with optimistic `expectedVersion` concurrency checks and `memorySha256` crash-recovery reconciliation). `` is injected only on a member's first wake, when `member.lastMemoryVersion !== room.memoryVersion`, or after that member's native Thread undergoes context compaction (tracked per `(roomId, threadId)` for actual group members and cleaned up after removal/rebind/deletion persists, which also re-injects the group rules block). If memory exceeds the remaining envelope budget, it is truncated with a CLI readback hint (`codexhost group memory read --format text`), or deferred without advancing `member.lastMemoryVersion` if a near-full roster leaves insufficient budget. - **Perspective flipping**: External room messages always arrive as `user` input with explicit `sender_type="user|agent"` tags; cross-vendor `tool_call_id` and `reasoning_signature` blocks are never forwarded. - **Busy-turn coalescing**: If a target native Thread is busy when mentioned (by a human or another agent), Host records a pending wake without interrupting the running Turn and delivers one coalesced delta once the Thread becomes idle. @@ -34,9 +35,10 @@ Multi-Harness Group Chat lets users bring multiple independent native Threads— - Enabling or switching `leaderMemberId` clears any queued `hop > 0` wakes that are no longer permitted under the new leader rule (non-leader → non-leader, or wakes dispatched by a previous leader to another non-leader), and `#eligible()` re-validates leader routing before dispatch. - Creating a room with `leaderMemberIndex` (when `unmentionedPolicy === "none"`) or enabling Leader Mode on an open room with no pinned default member automatically sets `unmentionedMemberId` to the leader and marks `leaderSyncedDefaultMember: true`, so switching leaders follows the new leader and clearing/removing the leader restores unmentioned messages to `none`. Any pre-existing or subsequently user-pinned `unmentionedMemberId` / `unmentionedPolicy` clears `leaderSyncedDefaultMember` and is preserved across leader switches and leader removal. - **Hard loop & safety bounds**: - - Agent-to-agent `@name` relay is controlled by room-level `allowAgentMentions` (default `true`) and halts at `maxAgentHops` (default `10`, range `0–200`, where `0` disables the hop breaker for unlimited relay), posting a system notice waiting for human input when a finite limit is reached. Persisted/wire room payloads keep `maxAgentHops` within `1–20` and carry `0` or `21–200` in optional `relayHopLimit` for forward compatibility with `v0.34.0` readers. + - Agent-to-agent `@name` relay is controlled by room-level `allowAgentMentions` (default `true`) and bounded by the room's customizable `maxAgentHops` (default `10`, range `0–200`, where `0` disables the breaker for unlimited relay). When finite (`> 0`), `maxAgentHops` enforces both the single-chain hop depth and the total number of newly enqueued automatic relay wakes within the same `(roomId, relayGeneration, epoch)` round to curb fan-out amplification, pausing the room (`relayPaused = true`) and posting a system notice waiting for human input when reached. Persisted/wire room payloads keep `maxAgentHops` within `1–20` and carry `0` or `21–200` in optional `relayHopLimit` for forward compatibility with `v0.34.0` readers. - Self-mentions are ignored; `@all` / `@所有人` is honored only for human messages and skips muted members. - - Any new human message increments `humanEpoch`, clears `relayPaused`, and wakes its targets at `hop = 0` without silently dropping relays from normally completing in-flight Turns. Explicit interruptions (`relayPaused: true`, `allowAgentMentions: false`, or hitting the hop breaker) advance the room's relay generation, clear queued `hop > 0` relays, refresh queued `hop = 0` human wakes to the new generation, and prevent pre-interruption in-flight group Turns from triggering further relays even after the room resumes. + - Any new human message increments `humanEpoch`, clears `relayPaused`, and wakes its targets at `hop = 0` without silently dropping relays from normally completing in-flight Turns. Explicit interruptions (`relayPaused: true`, `allowAgentMentions: false`, or hitting the hop/fan-out breaker) advance the room's relay generation, clear queued `hop > 0` relays, refresh queued `hop = 0` human wakes to the new generation, and prevent pre-interruption in-flight group Turns from triggering further relays even after the room resumes. + - Explicit room stop (`codexhost/groups/stop`) pauses automatic relays (`relayPaused = true`), advances both the room's relay generation and a dedicated stop generation, purges per-round relay budgets, and clears **all** pending room wakes (both `hop = 0` and `hop > 0`) while preventing wakes claimed prior to `stop()` from being re-enqueued on `THREAD_BUSY`. Legacy `v0.35.1` hosts/remote peers that do not implement `codexhost/groups/stop` gracefully fall back to `codexhost/groups/update` with `{ relayPaused: true }`. - Member permission approvals and questions surface back to the human without cross-member bypass. ## Persistence, RPCs, and CLI @@ -45,7 +47,7 @@ Multi-Harness Group Chat lets users bring multiple independent native Threads— - `.json` — `GroupRoom` metadata, settings, `memoryVersion`, and `members[]` (UUIDv4-validated filename). - `.messages.jsonl` — append-only public `GroupMessage` records supporting `fromSeq` / `toSeq` / `beforeSeq` / `limit` queries with corrupt-line tolerance. - `.memory.md` — optional shared room memory document (default `4 KiB` UTF-8, configurable `1–256 KiB` via `room.memoryMaxBytes`, removed when cleared; rolled back if saving `.json` fails, and reconciled via `memorySha256` if a crash occurs between file write and metadata save). -- **Shared Contracts (`packages/shared-contracts/src/group-chat.ts`)**: Exports all Zod schemas (including optional Leader Mode fields `leaderMemberId`, `leaderMemberIndex`, `leaderSyncedDefaultMember`, and `leaderClearedRosterVersion`, plus remote Peer capability `groupLeaderMode`), TypeScript types, `GROUPS_CHANGED_EVENT` (`codexhost/groups/changed`), `GROUP_NO_REPLY_MARKER` / `isGroupNoReply`, `GROUP_MEMORY_MAX_BYTES` / `GROUP_MEMORY_MIN_BYTES` / `GROUP_MEMORY_HARD_MAX_BYTES` / `resolveGroupMemoryMaxBytes`, and 14 `codexhost/groups/*` RPC methods (`list`, `get`, `create`, `update`, `delete`, `member/add`, `member/update`, `member/remove`, `member/rebind`, `message/post`, `messages/read`, `memory/read`, `memory/update`, `cwd/inspect` returning `{ isGitRepo, hasCommits?, hasHeadCommit?, autoInitGitSupported? }`), plus the CLI schemas for `group list`, `group member rebind`, `group memory read|update`, and system notices (`notice: true`, max 2,000 characters). +- **Shared Contracts (`packages/shared-contracts/src/group-chat.ts`)**: Exports all Zod schemas (including optional Leader Mode fields `leaderMemberId`, `leaderMemberIndex`, `leaderSyncedDefaultMember`, and `leaderClearedRosterVersion`, plus remote Peer capability `groupLeaderMode`), TypeScript types, `GROUPS_CHANGED_EVENT` (`codexhost/groups/changed`), `GROUP_NO_REPLY_MARKER` / `isGroupNoReply` / `hasGroupNoReplyDirective`, `GROUP_SINGLE_MESSAGE_MAX_BYTES` (`4 KiB`), `GROUP_MEMORY_MAX_BYTES` / `GROUP_MEMORY_MIN_BYTES` / `GROUP_MEMORY_HARD_MAX_BYTES` / `resolveGroupMemoryMaxBytes`, and 15 `codexhost/groups/*` RPC methods (`list`, `get`, `create`, `update`, `stop`, `delete`, `member/add`, `member/update`, `member/remove`, `member/rebind`, `message/post`, `messages/read`, `memory/read`, `memory/update`, `cwd/inspect` returning `{ isGitRepo, hasCommits?, hasHeadCommit?, autoInitGitSupported? }`), plus the CLI schemas for `group list`, `group member rebind`, `group memory read|update`, and system notices (`notice: true`, max 2,000 characters). - **CLI (`packages/host-runtime/src/group-cli.ts`, forwarded by `crates/launcher`)**: - `codexhost group list [--thread ] [--format text|json|compact]` — read-only (`/v1/group/list`, permitted for `read`-scope external clients); omits message bodies, filters to non-removed memberships with member metadata when `--thread` is given, and restricts managed member sessions (`agent`) to rooms they belong to. - `codexhost group read [--from ] [--to ] [--limit ] [--format text|json|compact]` @@ -65,7 +67,7 @@ Multi-Harness Group Chat lets users bring multiple independent native Threads— - **Direct jump navigation & member handoff**: Clicking a member status pill in the Group Chat header or **View process ↗** on a message jumps directly to that member's native Thread and displays a `← Back to Group` return pill in the conversation header. Handing off a group member—either directly from the member's `…` menu (**Hand off to another Agent**) or from inside the member's native Thread—automatically rebinds the group seat to the new Thread (preserving identity, Role instructions/snapshot, `showInSidebar`, and unread message cursor), delivers the verified `` on the next group wake while isolating private 1:1 injections, and keeps `← Back to Group` synced. - **In-place right workspace sidebar**: The Group Chat panel binds its active room's backing member Session to `ctx.sidebarRight.registerPanelSession(GROUP_CHAT_PANEL_ID, ...)`. Users can open/collapse the Workspace sidebar directly from the Group Chat header (or click the workspace pill to jump to the Files tree), and clicking file, video, audio, image, or directory links in group messages previews them directly inside the Group Chat right sidebar without switching away to a member's 1:1 Thread. - **Shared room memory modal (`GroupMemoryModal.tsx`)**: The Group Chat header exposes a **Memory** button (with a `v` version pill when populated; omitted for remote Peers that do not advertise `groupSharedMemory`). Opening the modal loads `.memory.md`, displays version and UTF-8 byte usage, flags concurrent out-of-date updates via a status banner, guards in-flight reads/saves by request sequence and active `roomId`, and supports Refresh, Clear, and Save (`Cmd/Ctrl+Enter`) with optimistic `expectedVersion` checks. Per-room memory limit configuration in **Group settings** (`memoryMaxBytes`, 1–256 KiB) is shown only for local rooms and remote Peers advertising `groupSharedMemoryMaxBytes`. -- **Live process awareness & stop controls**: While the Group Chat panel is active, `GroupLiveObserver` retains up to 6 active member Threads (`groupLivePreview`) to show a compact 1-line progress row per working member, warm-amber `Needs You` highlights, live streaming Markdown reply cards (with a brief post-turn grace handoff), and persisted `durationMs` on completed agent replies. Each active live card exposes a per-member **Stop** button (`session.cancel()`), and the composer switches its primary button to **Stop** when members are running and the draft is empty; cancelling suppresses the post-turn streaming grace window so stopped cards clear immediately. +- **Live process awareness & stop controls**: While the Group Chat panel is active, `GroupLiveObserver` retains up to 6 active member Threads (`groupLivePreview`) to show a compact 1-line progress row per working member, warm-amber `Needs You` highlights, live streaming Markdown reply cards (with a brief post-turn grace handoff), and persisted `durationMs` on completed agent replies. Each active live card exposes a per-member **Stop** button (`session.cancel()` directly on that member's Thread, without calling the room stop RPC), and the composer switches its primary button to **Stop / Stop all** when members are running and the draft is empty. Clicking **Stop / Stop all** synchronously captures each target's click-time open `turnKey` from `GroupLiveObserver`'s retained slots—or transiently from any Session already live elsewhere in the client (`retainInfo().referenceCount > 0`) without creating a new scope or running async probes that could misattribute a later Turn—and waits for `codexhost/groups/stop` to settle before cancelling active member Turns: on current Hosts, `codexhost/groups/stop` persists `relayPaused: true` and clears all pending room wakes; on legacy `v0.35.1` Hosts/Peers that lack the stop RPC, it falls back to `codexhost/groups/update` (`{ relayPaused: true }`), pausing automatic relays without clearing queued wakes; if the room stop RPC fails, the page retains an error banner with a one-click retry action while still attempting to stop confirmed active Turns (merging off-room stop-failure and skipped-member notices so neither overwrites the other). After the room stop settles, confirmed targets are re-checked by their captured `turnKey` (including after switching away and back to the same room) and cancelled if still open—targets whose Turn identity could not be confirmed synchronously at click time are skipped (with a notice to stop them individually if still running), and accepted cancellations suppress the post-turn streaming grace window so stopped cards clear immediately. Note that the underlying shared `session/cancel` RPC carries only `sessionId` (not a native Host `turnId`), so client-side `turnKey` verification guards the pre-dispatch window while server-side cancel remains session-scoped. - **Composer controls**: Aligns with the restrained native Thread composer visual tokens and includes a name-first member-avatar quick-pick bar (`@name` chips + `@all`, hiding internal handles/IDs), `@` autocomplete, one-click message reply, a live bottom-toolbar reply-target indicator and persistent default picker (`Reply: ` / `回复: <目标>`), and a top `Needs You` banner aggregating blocked member approvals/questions: - **Live target derivation (`reply-target.ts`)**: Serializes structured mention spans and hand-typed `@displayName` / `@handle` / `@all` / `@所有人` outside Markdown fenced, indented, and inline code (via shared `maskGroupMentionCode`) into Host-readable mention links, then derives the live bottom-toolbar target from that exact serialized payload—explicit `@` mentions (including stale mentions to muted or removed members) override the saved room default for that message without mutating room settings, while unmentioned drafts resolve `unmentionedMemberId` (when set) or `unmentionedPolicy` (`last_speaker`, `all`, or `none`). - **Single-selection persistent default menu**: Clicking the bottom-toolbar indicator opens a deduplicated two-section menu—active members (plus the pinned member if currently muted) in the upper section to pin a fixed default reply member (`unmentionedPolicy: "none"` + `unmentionedMemberId`), and the three general room defaults (`none`, `last_speaker`, `all`) in the lower section—with strictly one checkmark on the active default, serialized latest-wins updates, and explicit rollback/error feedback on failure. The Group Chat Settings popover exposes the same unified selector. diff --git a/packages/host-runtime/src/app-server-host.ts b/packages/host-runtime/src/app-server-host.ts index b580c889c1..c25409bbd8 100644 --- a/packages/host-runtime/src/app-server-host.ts +++ b/packages/host-runtime/src/app-server-host.ts @@ -1088,6 +1088,36 @@ function isPassiveTelemetryOutput(output: HarnessOutput): boolean { } } +const OFFICIAL_BLOCKING_SERVER_REQUEST_PATTERN = + /requestApproval|requestUserInput|elicitation\/request|review\/request/u; + +function officialServerRequestThreadId(params: unknown): string | undefined { + if (!isRecord(params)) return undefined; + if (typeof params.threadId === "string" && params.threadId.length > 0) return params.threadId; + if ( + isRecord(params.thread) && + typeof params.thread.id === "string" && + params.thread.id.length > 0 + ) { + return params.thread.id; + } + if ( + isRecord(params.turn) && + typeof params.turn.threadId === "string" && + params.turn.threadId.length > 0 + ) { + return params.turn.threadId; + } + if ( + isRecord(params.item) && + typeof params.item.threadId === "string" && + params.item.threadId.length > 0 + ) { + return params.item.threadId; + } + return undefined; +} + /** Native thread/read may omit `archived` and signal archive state via the rollout path. */ function isArchivedOfficialThread(thread: Record): boolean { if (thread.archived === true) return true; @@ -1177,6 +1207,7 @@ export class AppServerHost { readonly #officialRateLimits = new AccountRateLimits(); #routeObservationTracker = new RequestRouteObservationTracker(); #officialServerRequests = new Map(); + #officialBlockingRequests = new Map(); #nextOfficialServerRequestId = 0; #writer: OrderedWriter; readonly clientEvents = new ClientChannelEvents(); @@ -1420,6 +1451,7 @@ export class AppServerHost { this.#signalActiveWorkChanged(); // A retired process can neither answer nor resolve its server requests. this.#officialServerRequests.clear(); + this.#officialBlockingRequests.clear(); this.#groups?.releaseFlights((threadId) => !this.#externalRuntime.get(threadId)); void this.#questions.closeWhere((request) => request.harnessId === "codex"); }, @@ -1624,6 +1656,12 @@ export class AppServerHost { maintenanceOperation(() => this.#startGroupTurn(id, context, claimWake, imagePaths)), activeTurn: (id) => this.#externalRuntime.get(id)?.activeTurnId ?? this.#liveActiveOfficialTurnId(id), + isBlocked: (id) => + [...this.#pendingDesktopApprovals.values()].some(({ thread }) => thread.id === id) || + [...this.#pendingDesktopQuestions.values()].some(({ thread }) => thread.id === id) || + [...this.#officialBlockingRequests.values()].includes(id) || + this.#client.hasNativeInteractions(id) || + this.#pendingDelegationQuestions(id).length > 0, changed: (roomId) => { this.clientEvents.groupsChanged(roomId); void this.#writer @@ -3305,6 +3343,7 @@ export class AppServerHost { const original = this.#officialServerRequests.get(requestId); if (original === undefined) return false; this.#officialServerRequests.delete(requestId); + this.#officialBlockingRequests.delete(requestId); this.#treeWatch.resolveOfficial(original); await this.#officialRuntime.send({ ...response, id: original }); return true; @@ -3390,6 +3429,12 @@ export class AppServerHost { if (typeof originalId === "string" || typeof originalId === "number") { const forwardedId = `codexhost:official:${++this.#nextOfficialServerRequestId}`; this.#officialServerRequests.set(forwardedId, originalId); + if (OFFICIAL_BLOCKING_SERVER_REQUEST_PATTERN.test(parsed.method)) { + const requestThreadId = officialServerRequestThreadId(parsed.params); + if (requestThreadId !== undefined) { + this.#officialBlockingRequests.set(forwardedId, requestThreadId); + } + } forwarded = { ...parsed, id: forwardedId }; } } @@ -3507,10 +3552,17 @@ export class AppServerHost { } } + #clearOfficialBlockingRequestsForThread(threadId: string): void { + for (const [requestId, trackedThreadId] of this.#officialBlockingRequests) { + if (trackedThreadId === threadId) this.#officialBlockingRequests.delete(requestId); + } + } + #finishOfficialTurn(value: JsonValue): void { if (!isRecord(value) || value.method !== "turn/completed" || !isRecord(value.params)) return; const { threadId, turn } = value.params; if (typeof threadId !== "string" || !isRecord(turn)) return; + this.#clearOfficialBlockingRequestsForThread(threadId); // Run after output is flushed (or immediately for the non-rendering owner). // An old terminal must never clear a newer active Turn. if (this.#activeOfficialTurns.get(threadId) === turn.id) @@ -3596,6 +3648,15 @@ export class AppServerHost { #observeOfficialServerRequest(parsed: JsonValue, forwarded: JsonValue): JsonValue | null { if (!isRecord(forwarded)) return forwarded; const params = forwarded.params; + if ( + (forwarded.method === "thread/closed" || forwarded.method === "thread/deleted") && + isRecord(params) + ) { + const closedThreadId = officialServerRequestThreadId(params); + if (closedThreadId !== undefined) { + this.#clearOfficialBlockingRequestsForThread(closedThreadId); + } + } if ( forwarded.method === "item/tool/requestUserInput" && typeof forwarded.id === "string" && @@ -3612,6 +3673,7 @@ export class AppServerHost { request: params as JsonObject, retire: () => { this.#officialServerRequests.delete(requestId); + this.#officialBlockingRequests.delete(requestId); }, respond: async (reply) => { if (await this.#replyToOfficialServerRequest(requestId, reply)) return; @@ -3631,6 +3693,7 @@ export class AppServerHost { for (const [requestId, originalId] of this.#officialServerRequests) { if (originalId !== parsed.params.requestId) continue; this.#officialServerRequests.delete(requestId); + this.#officialBlockingRequests.delete(requestId); void this.#questions.close(requestId, false); return { ...forwarded, diff --git a/packages/host-runtime/src/client-channel-host.ts b/packages/host-runtime/src/client-channel-host.ts index 8f9f8da0ba..fe311a79df 100644 --- a/packages/host-runtime/src/client-channel-host.ts +++ b/packages/host-runtime/src/client-channel-host.ts @@ -248,6 +248,10 @@ export class ClientChannelHost { }); } + hasNativeInteractions(threadId: string): boolean { + return (this.#native?.interactions(threadId)?.length ?? 0) > 0; + } + nativeChannel(): NativeClientChannel { if (!this.#native) throw new Error("Native client channel is unavailable"); return this.#native; diff --git a/packages/host-runtime/src/group-context-packer.ts b/packages/host-runtime/src/group-context-packer.ts index 4905d7f22b..db4d45d9c2 100644 --- a/packages/host-runtime/src/group-context-packer.ts +++ b/packages/host-runtime/src/group-context-packer.ts @@ -1,6 +1,7 @@ import { GROUP_CONTEXT_MAX_BYTES, GROUP_NO_REPLY_MARKER, + GROUP_SINGLE_MESSAGE_MAX_BYTES, type GroupMember, type GroupMessage, type GroupRoom, @@ -8,7 +9,7 @@ import { export interface GroupMemberActivity { readonly memberId: string; - readonly state: "working" | "queued"; + readonly state: "working" | "blocked" | "queued"; } export interface GroupContextMemory { @@ -21,6 +22,7 @@ export interface PackGroupContextOptions { readonly includeMemory?: boolean | undefined; readonly forceRules?: boolean | undefined; readonly activities?: readonly GroupMemberActivity[] | undefined; + readonly supersededBySelfSeq?: number | undefined; } const bytes = (text: string) => Buffer.byteLength(text, "utf8"); @@ -39,6 +41,19 @@ function omission(room: GroupRoom, seq: number | string): string { return `\n`; } +function truncateEscaped(text: string, maxBytes: number): string { + if (maxBytes <= 0) return ""; + let budget = maxBytes; + let excerpt = ""; + for (const point of text) { + const escaped = escape(point); + budget -= bytes(escaped); + if (budget < 0) break; + excerpt += escaped; + } + return excerpt; +} + const LEADER_MODE_OFF_SENTENCE = "Leader mode is now off: you may @mention any teammate freely again."; @@ -91,11 +106,13 @@ function rulesBlock( ): string { const leaderRule = leaderRuleSentence(room, self); return ( - `Public group chat: reply directly to the group. Write @Name to wake a teammate. ` + - `Everyone you @mention in one message starts immediately in parallel. For ordered steps (such as fix then review), only @mention the person who should act now, and write later teammates' names without @. ` + - `Avoid @mentioning teammates already marked working or queued in unless strictly necessary; refer to them without @ instead. ` + + `Public group chat: reply directly to the group. Write @Name ONLY when you need that teammate to act next. ` + + `Do NOT put @ before names when quoting, thanking, reporting status, or naming later teammates—use plain names without @. ` + + `Eligible teammates you @mention in one message can run in parallel (subject to busy queueing, blocked state, and the relay budget). For ordered steps (such as fix then review), only @mention the person who should act now. ` + + `Avoid @mentioning teammates marked working, blocked, or queued in ; refer to them without @ instead. ` + `${leaderRule ? `${escape(leaderRule)} ` : ""}` + `If no new action or substantive reply is needed from you, output only ${GROUP_NO_REPLY_MARKER} to stay silent. ` + + `Keep group replies concise: put long reports or large diffs in workspace files or shared room memory and post only a short summary with paths. ` + `Shared room memory: run "$CODEXHOST_CLI_PATH" group memory read|update ${room.roomId} to sync durable decisions, goals, or handoff state across all harnesses (keep concise).\n` ); } @@ -114,7 +131,7 @@ function activityBlock( if (entry.memberId === selfMemberId) continue; const name = byId.get(entry.memberId); if (!name) continue; - items.push(`@${name} (${entry.state})`); + items.push(`${name} (${entry.state})`); } if (!items.length) return ""; return `${escape(`busy: ${items.join(", ")}`)}\n`; @@ -160,7 +177,7 @@ function header( includeRoster: boolean, activities?: readonly GroupMemberActivity[], ): string { - let result = `\n`; + let result = `\n`; if (includeRules) { result += rulesBlock(room, self); } @@ -205,40 +222,161 @@ export function groupRosterFits(room: GroupRoom): boolean { ); } -function messageParts(message: GroupMessage) { - const from = message.senderName - ? `@${message.senderName}` - : message.senderHandle - ? `@${message.senderHandle}` - : "user"; +const MAX_TRUNCATED_FROM_BYTES = 128; + +function messageParts(message: GroupMessage, fromOverride?: string) { + const from = fromOverride ?? (message.senderName || message.senderHandle || "user"); return [ ``, "\n", ] as const; } -const MAX_GROUP_TURN_IMAGES = 8; -const MIN_MESSAGES_BUDGET_BYTES = 512; +function truncateAttributeValue(value: string, maxEscapedBytes: number): string { + if (maxEscapedBytes <= 0) return ""; + let budget = maxEscapedBytes; + let out = ""; + for (const point of value) { + const encoded = escape(point).replace(/\r|\n|\t/gu, (c) => `&#${c.charCodeAt(0)};`); + budget -= bytes(encoded); + if (budget < 0) break; + out += point; + } + return out; +} -function formatMessageBody(message: GroupMessage): string { - const parts: string[] = []; - if (message.content) parts.push(message.content); +function perMessageTruncationSuffix(room: GroupRoom, seq: number, hasAttachments = false): string { + const format = hasAttachments ? "json" : "text"; + return `\n… [truncated; run "$CODEXHOST_CLI_PATH" group read ${escape(room.roomId)} --from ${seq} --to ${seq} --format ${format}]`; +} + +function formatAttachmentLines(message: GroupMessage): string[] { + const lines: string[] = []; for (const attachment of message.attachments ?? []) { - parts.push( + lines.push( attachment.kind === "image" ? `[image: ${attachment.name} path="${attachment.path}"]` : `[file: ${attachment.name} path="${attachment.path}" bytes="${attachment.bytes}"]`, ); } + return lines; +} + +function formatMessageBody(message: GroupMessage): string { + const parts: string[] = []; + if (message.content) parts.push(message.content); + parts.push(...formatAttachmentLines(message)); return parts.join("\n"); } +function resolveTruncatedMessageEnvelope( + msg: GroupMessage, + maxBytes: number, + reservedBytes: number, +): { readonly open: string; readonly close: string; readonly budget: number } | null { + let [open, close] = messageParts(msg); + let budget = maxBytes - bytes(open) - bytes(close) - reservedBytes; + if (budget < 0) { + const rawFrom = msg.senderName || msg.senderHandle || "user"; + const clippedFrom = `${truncateAttributeValue(rawFrom, MAX_TRUNCATED_FROM_BYTES)}…`; + [open, close] = messageParts(msg, clippedFrom); + budget = maxBytes - bytes(open) - bytes(close) - reservedBytes; + } + if (budget < 0) { + [open, close] = messageParts(msg, "…"); + budget = maxBytes - bytes(open) - bytes(close) - reservedBytes; + } + return budget >= 0 ? { open, close, budget } : null; +} + +function serializeTruncatedMessageForBudget( + msg: GroupMessage, + maxBytes: number, + truncation: string, +): string | null { + const envelope = resolveTruncatedMessageEnvelope(msg, maxBytes, bytes(truncation)); + if (envelope === null) return null; + const attachmentLines = formatAttachmentLines(msg); + if (attachmentLines.length > 0) { + const hasText = msg.content.length > 0; + const keptAttachments: string[] = []; + let attachmentBytes = 0; + for (const line of attachmentLines) { + const escapedLine = escape(line); + const separatorBytes = keptAttachments.length > 0 || hasText ? 1 : 0; + const needed = separatorBytes + bytes(escapedLine); + if (attachmentBytes + needed > envelope.budget) break; + keptAttachments.push(escapedLine); + attachmentBytes += needed; + } + if (keptAttachments.length > 0) { + if (hasText) { + const attachmentTail = `\n${keptAttachments.join("\n")}`; + const textBudget = envelope.budget - bytes(attachmentTail); + return `${envelope.open}${truncateEscaped(msg.content, textBudget)}${truncation}${attachmentTail}${envelope.close}`; + } + return `${envelope.open}${keptAttachments.join("\n")}${truncation}${envelope.close}`; + } + } + return `${envelope.open}${truncateEscaped(formatMessageBody(msg), envelope.budget)}${truncation}${envelope.close}`; +} + +function serializeMessageWithinBudget( + room: GroupRoom, + msg: GroupMessage, + maxBytes: number, +): { readonly serialized: string; readonly truncated: boolean } | null { + const body = formatMessageBody(msg); + const [open, close] = messageParts(msg); + const full = `${open}${escape(body)}${close}`; + if (bytes(full) <= maxBytes) { + return { serialized: full, truncated: false }; + } + const hasAttachments = (msg.attachments?.length ?? 0) > 0; + const preferredTruncation = perMessageTruncationSuffix(room, msg.seq, hasAttachments); + const withPreferred = serializeTruncatedMessageForBudget(msg, maxBytes, preferredTruncation); + if (withPreferred !== null) { + return { serialized: withPreferred, truncated: true }; + } + const withCompactNewline = serializeTruncatedMessageForBudget(msg, maxBytes, "\n… [truncated]"); + if (withCompactNewline !== null) { + return { serialized: withCompactNewline, truncated: true }; + } + const withCompact = serializeTruncatedMessageForBudget(msg, maxBytes, "… [truncated]"); + if (withCompact !== null) { + return { serialized: withCompact, truncated: true }; + } + return null; +} + +function serializeUnreadMessage( + room: GroupRoom, + msg: GroupMessage, +): { readonly serialized: string; readonly truncated: boolean } { + const fitted = serializeMessageWithinBudget(room, msg, GROUP_SINGLE_MESSAGE_MAX_BYTES); + if (fitted !== null) return fitted; + const [fallbackOpen, fallbackClose] = messageParts(msg, "…"); + return { + serialized: `${fallbackOpen}… [truncated]${fallbackClose}`, + truncated: true, + }; +} + +const MAX_GROUP_TURN_IMAGES = 8; +const MIN_MESSAGES_BUDGET_BYTES = 512; + export function packGroupContextWithImages( room: GroupRoom, member: GroupMember, messages: readonly GroupMessage[], options?: PackGroupContextOptions, -): { context: string; imagePaths: string[]; memoryDelivered: boolean } { +): { + context: string; + imagePaths: string[]; + memoryDelivered: boolean; + packedMessageCount: number; + unreadMessageCount: number; +} { const isFirstWake = member.lastRosterVersion === 0; const includeRules = isFirstWake || options?.forceRules === true; const rosterChanged = member.lastRosterVersion !== room.rosterVersion; @@ -256,6 +394,20 @@ export function packGroupContextWithImages( GROUP_CONTEXT_MAX_BYTES ? basePrefixWithActivity : basePrefixWithoutActivity; + const rawSupersededNote = + options?.supersededBySelfSeq !== undefined + ? `${escape(`These messages arrived before your latest reply (seq ${options.supersededBySelfSeq}). If your reply already covers them, output only ${GROUP_NO_REPLY_MARKER}.`)}\n` + : ""; + const supersededNote = + rawSupersededNote.length > 0 && + bytes(basePrefix) + + bytes(rawSupersededNote) + + envelopeOverhead + + omissionOverhead + + MIN_MESSAGES_BUDGET_BYTES <= + GROUP_CONTEXT_MAX_BYTES + ? rawSupersededNote + : ""; const includeMemory = options?.includeMemory ?? (options?.memory !== undefined && @@ -264,6 +416,7 @@ export function packGroupContextWithImages( 0, GROUP_CONTEXT_MAX_BYTES - bytes(basePrefix) - + bytes(supersededNote) - envelopeOverhead - omissionOverhead - MIN_MESSAGES_BUDGET_BYTES, @@ -274,7 +427,7 @@ export function packGroupContextWithImages( options?.memory !== undefined && (options.memory.content.trim().length > 0 || options.memory.version > 0); const memoryDelivered = !memoryExpected || memorySection.length > 0; - const prefix = `${basePrefix}${memorySection}`; + const prefix = `${basePrefix}${memorySection}${supersededNote}`; const available = GROUP_CONTEXT_MAX_BYTES - bytes(prefix) - envelopeOverhead; const unread = messages.filter( (msg) => @@ -289,9 +442,7 @@ export function packGroupContextWithImages( let omittedThrough = 0; for (let index = unread.length - 1; index >= 0; index--) { const msg = unread[index]!; - const body = formatMessageBody(msg); - const [open, close] = messageParts(msg); - const serialized = `${open}${escape(body)}${close}`; + const { serialized } = serializeUnreadMessage(room, msg); const needed = bytes(serialized) + (index > 0 ? bytes(omission(room, unread[index - 1]!.seq)) : 0); if (needed <= remaining) { @@ -302,17 +453,10 @@ export function packGroupContextWithImages( } omittedThrough = msg.seq; if (!packed.length) { - const truncation = "… [truncated]"; - let budget = remaining - bytes(omission(room, msg.seq)) - bytes(open + close + truncation); - if (budget >= 0) { - let excerpt = ""; - for (const point of body) { - const escaped = escape(point); - budget -= bytes(escaped); - if (budget < 0) break; - excerpt += escaped; - } - packed.push(`${open}${excerpt}${truncation}${close}`); + const fallbackBudget = remaining - bytes(omission(room, msg.seq)); + const fallbackFitted = serializeMessageWithinBudget(room, msg, fallbackBudget); + if (fallbackFitted !== null) { + packed.push(fallbackFitted.serialized); packedMessages.push(msg); } } @@ -335,7 +479,13 @@ export function packGroupContextWithImages( imagePaths.unshift(...messagePaths); if (imagePaths.length >= MAX_GROUP_TURN_IMAGES) break; } - return { context, imagePaths, memoryDelivered }; + return { + context, + imagePaths, + memoryDelivered, + packedMessageCount: packedMessages.length, + unreadMessageCount: unread.length, + }; } export function packGroupContext( diff --git a/packages/host-runtime/src/group-room-host.ts b/packages/host-runtime/src/group-room-host.ts index 0e305eed15..c12e7c6424 100644 --- a/packages/host-runtime/src/group-room-host.ts +++ b/packages/host-runtime/src/group-room-host.ts @@ -7,9 +7,12 @@ import { GROUP_NOTICE_MAX_LENGTH, encodeGroupMaxAgentHops, groupUtf8ByteLength, + hasGroupNoReplyDirective, isGroupNoReply, + maskGroupMentionCode, resolveGroupMaxAgentHops, resolveGroupMemoryMaxBytes, + splitGroupMentionSegments, type GroupCliListEntry, type GroupCliListMember, type GroupCliListResult, @@ -29,6 +32,8 @@ import { type GroupsRebindMemberParams, type GroupsRebindMemberResult, type GroupsRemoveMemberParams, + type GroupsStopParams, + type GroupsStopResult, type GroupsUpdateMemberParams, type GroupsUpdateMemoryParams, type GroupsUpdateMemoryResult, @@ -75,6 +80,7 @@ interface GroupRoomHostOptions extends GroupMemberThreads { imagePaths?: readonly string[], ): Promise; activeTurn(threadId: string): string | null | undefined; + isBlocked?: (threadId: string) => boolean; changed(roomId: string): void; diagnose(error: unknown): void; } @@ -85,6 +91,7 @@ interface Wake { epoch: number; hop: number; relayGeneration: number; + triggerSeq?: number | undefined; } type FinalText = () => string | undefined | Promise; interface Flight { @@ -95,8 +102,15 @@ interface Flight { turnId?: string; early: Map; completing?: boolean; + cliPostedContents: string[]; + cliAwakenedMemberIds: Set; +} +interface PublishOptions { + readonly viaCli?: boolean; + readonly suppressMemberIds?: ReadonlySet; } +const MAX_RELAY_BUDGET_ENTRIES = 512; const now = () => new Date().toISOString(); const sha256Hex = (text: string) => createHash("sha256").update(text, "utf8").digest("hex"); const invalid = (message: string) => new DelegationControlError("INVALID_ARGUMENT", message); @@ -107,7 +121,46 @@ const nonBlankErrorMessage = (error: unknown, fallback: string): string => { }; const roomMemberKey = (roomId: string, memberId: string) => `${roomId}:${memberId}`; const roomThreadKey = (roomId: string, threadId: string) => `${roomId}\0${threadId}`; +const relayBudgetKey = (roomId: string, relayGeneration: number, epoch: number) => + `${roomId}:${relayGeneration}:${epoch}`; const wakeKey = (wake: Wake) => roomMemberKey(wake.roomId, wake.memberId); +function normalizeComparableGroupText( + text: string, + members: readonly GroupMember[], + senderMemberId?: string, +): string { + const canonical = canonicalizeAgentGroupMentions(text, members, senderMemberId); + const byMemberId = new Set(); + const byHandle = new Map(); + for (const member of members) { + if (member.status === "removed") continue; + byMemberId.add(member.memberId); + const handle = member.handle.trim().toLowerCase(); + if (handle.length > 0) byHandle.set(handle, member.memberId); + } + for (const member of members) { + if (member.status !== "removed") continue; + byMemberId.add(member.memberId); + const handle = member.handle.trim().toLowerCase(); + if (handle.length > 0 && !byHandle.has(handle)) byHandle.set(handle, member.memberId); + } + let normalized = ""; + let offset = 0; + for (const segment of splitGroupMentionSegments(maskGroupMentionCode(canonical))) { + if (segment.kind === "mention") { + const target = segment.target.trim(); + const resolved = byMemberId.has(target) + ? target + : (byHandle.get(target.toLowerCase()) ?? target); + normalized += `\0mention:${resolved}\0`; + offset += segment.raw.length; + } else { + normalized += canonical.slice(offset, offset + segment.text.length); + offset += segment.text.length; + } + } + return normalized.replace(/\r\n?/gu, "\n").trim(); +} export class GroupRoomHost { readonly #locks = new Map>(); @@ -116,7 +169,12 @@ export class GroupRoomHost { readonly #pumps = new Set(); readonly #nudged = new Set(); readonly #handoffPausedThreads = new Set(); + readonly #stoppingRooms = new Set(); + readonly #pausingRelayRooms = new Set(); readonly #relayGenerations = new Map(); + readonly #stopGenerations = new Map(); + readonly #roomCurrentEpochs = new Map(); + readonly #relayBudgets = new Map(); readonly #memberBindingGenerations = new Map(); readonly #roomIndexRevisions = new Map(); readonly #compactedRoomThreads = new Map(); @@ -138,7 +196,12 @@ export class GroupRoomHost { this.#pending.clear(); this.#flights.clear(); this.#handoffPausedThreads.clear(); + this.#stoppingRooms.clear(); + this.#pausingRelayRooms.clear(); this.#relayGenerations.clear(); + this.#stopGenerations.clear(); + this.#roomCurrentEpochs.clear(); + this.#relayBudgets.clear(); this.#memberBindingGenerations.clear(); this.#roomIndexRevisions.clear(); this.#compactedRoomThreads.clear(); @@ -169,6 +232,10 @@ export class GroupRoomHost { #syncRoomMembershipIndex(room: GroupRoom): void { if (this.#closed) return; + const prevEpoch = this.#roomCurrentEpochs.get(room.roomId) ?? -1; + if (room.humanEpoch > prevEpoch) { + this.#roomCurrentEpochs.set(room.roomId, room.humanEpoch); + } const prevThreads = this.#roomMemberThreads.get(room.roomId); const nextThreads = new Set(); for (const member of room.members) { @@ -317,9 +384,58 @@ export class GroupRoomHost { return this.#relayGenerations.get(roomId) ?? 0; } + #purgeRoomRelayBudgets(roomId: string): void { + const prefix = `${roomId}:`; + for (const key of this.#relayBudgets.keys()) { + if (key.startsWith(prefix)) this.#relayBudgets.delete(key); + } + } + + #activeRelayBudgetKeys(): Set { + const active = new Set(); + for (const [roomId, epoch] of this.#roomCurrentEpochs) { + active.add(relayBudgetKey(roomId, this.#relayGeneration(roomId), epoch)); + } + for (const flight of this.#flights.values()) { + active.add( + relayBudgetKey(flight.wake.roomId, flight.wake.relayGeneration, flight.wake.epoch), + ); + } + for (const wakes of this.#pending.values()) { + for (const wake of wakes.values()) { + active.add(relayBudgetKey(wake.roomId, wake.relayGeneration, wake.epoch)); + } + } + return active; + } + + #recordRelayBudget(key: string, used: number): void { + this.#relayBudgets.delete(key); + this.#relayBudgets.set(key, used); + if (this.#relayBudgets.size <= MAX_RELAY_BUDGET_ENTRIES) return; + const activeKeys = this.#activeRelayBudgetKeys(); + for (const oldest of this.#relayBudgets.keys()) { + if (this.#relayBudgets.size <= MAX_RELAY_BUDGET_ENTRIES) break; + if (oldest === key || activeKeys.has(oldest)) continue; + this.#relayBudgets.delete(oldest); + } + } + + #wakeRoomPendingThreads(roomId: string): void { + for (const [threadId, wakes] of this.#pending) { + for (const wake of wakes.values()) { + if (wake.roomId === roomId) { + this.threadIdle(threadId); + break; + } + } + } + } + #interruptRelays(roomId: string): number { const next = this.#relayGeneration(roomId) + 1; this.#relayGenerations.set(roomId, next); + this.#purgeRoomRelayBudgets(roomId); for (const [threadId, wakes] of this.#pending) { for (const [key, wake] of wakes) { if (wake.roomId !== roomId) continue; @@ -762,10 +878,22 @@ export class GroupRoomHost { if (patch.pinned !== undefined) room.pinned = patch.pinned; if (patch.relayPaused !== undefined) room.relayPaused = patch.relayPaused; validateGroupRoster(room); - const saved = await this.#save(room); + const interruptsRelays = patch.relayPaused === true || patch.allowAgentMentions === false; + if (interruptsRelays) this.#pausingRelayRooms.add(roomId); + let saved: GroupRoom; + try { + saved = await this.#save(room); + } catch (error) { + if (interruptsRelays) { + this.#pausingRelayRooms.delete(roomId); + this.#wakeRoomPendingThreads(roomId); + } + throw error; + } const maxAgentHops = resolveGroupMaxAgentHops(saved); - if (patch.relayPaused === true || patch.allowAgentMentions === false) { + if (interruptsRelays) { this.#interruptRelays(roomId); + this.#pausingRelayRooms.delete(roomId); } else { this.#clearPending( roomId, @@ -781,12 +909,48 @@ export class GroupRoomHost { }); } + #stopGeneration(roomId: string): number { + return this.#stopGenerations.get(roomId) ?? 0; + } + + stop({ roomId }: GroupsStopParams): Promise { + return this.#lock(roomId, async () => { + const room = await this.#room(roomId); + this.#stoppingRooms.add(roomId); + room.relayPaused = true; + let saved: GroupRoom; + try { + saved = await this.#save(room); + } catch (error) { + this.#stoppingRooms.delete(roomId); + this.#wakeRoomPendingThreads(roomId); + throw error; + } + const clearedMemberIds = new Set(); + this.#stopGenerations.set(roomId, this.#stopGeneration(roomId) + 1); + this.#relayGenerations.set(roomId, this.#relayGeneration(roomId) + 1); + this.#purgeRoomRelayBudgets(roomId); + this.#clearPending(roomId, (wake) => { + clearedMemberIds.add(wake.memberId); + return true; + }); + this.#stoppingRooms.delete(roomId); + return { + room: saved, + clearedPendingMemberIds: [...clearedMemberIds], + }; + }); + } + delete({ roomId }: { roomId: string }) { return this.#lock(roomId, async () => { const deleted = await this.options.store.deleteGroupRoom(roomId); this.#roomIndexRevisions.set(roomId, ++this.#nextRoomIndexRevision); this.#clearPending(roomId, () => true); this.#relayGenerations.delete(roomId); + this.#stopGenerations.delete(roomId); + this.#roomCurrentEpochs.delete(roomId); + this.#purgeRoomRelayBudgets(roomId); this.#purgeRoomBindingGenerations(roomId); this.#purgeRoomCompaction(roomId); if (deleted) this.options.changed(roomId); @@ -1330,6 +1494,8 @@ export class GroupRoomHost { }, member, member ? this.#flights.get(member.threadId) : undefined, + undefined, + { viaCli: true }, ); }); } @@ -1381,6 +1547,7 @@ export class GroupRoomHost { sender?: GroupMember, flight?: Flight, sourceTurnId?: string, + publishOptions?: PublishOptions, ) { const senderType = sender ? "agent" : "user"; const content = sender @@ -1413,6 +1580,16 @@ export class GroupRoomHost { ? active.filter((m) => m.memberId === room.lastSpeakerMemberId) : []; } + if (sender) { + if (hasGroupNoReplyDirective(content)) { + targets = []; + } else { + const suppressed = publishOptions?.suppressMemberIds; + targets = targets.filter( + (m) => !suppressed?.has(m.memberId) && !this.options.isBlocked?.(m.threadId), + ); + } + } const activeTurn = sender ? this.options.activeTurn(sender.threadId) : undefined; const matchingFlight = flight?.turnId && (sourceTurnId ?? activeTurn) === flight.turnId ? flight : undefined; @@ -1436,9 +1613,25 @@ export class GroupRoomHost { ? wake.roomId === room.roomId && wake.memberId === sender.memberId : !flight && Boolean(activeTurn))); const maxAgentHops = resolveGroupMaxAgentHops(room); - const breaker = Boolean( + const budgetKey = relayBudgetKey(room.roomId, relayGeneration, epoch); + const usedRelays = sender ? (this.#relayBudgets.get(budgetKey) ?? 0) : 0; + const newRelayTargets = sender + ? targets.filter( + (m) => !this.#pending.get(m.threadId)?.has(roomMemberKey(room.roomId, m.memberId)), + ) + : targets; + const hopLimitHit = Boolean( sender && relayAllowed && targets.length && maxAgentHops > 0 && hop >= maxAgentHops, ); + const budgetLimitHit = Boolean( + sender && + relayAllowed && + !hopLimitHit && + newRelayTargets.length > 0 && + maxAgentHops > 0 && + usedRelays + newRelayTargets.length > maxAgentHops, + ); + const breaker = hopLimitHit || budgetLimitHit; const message = await this.#append(room, { senderType, content, @@ -1467,16 +1660,65 @@ export class GroupRoomHost { room.relayPaused = true; await this.#append(room, { senderType: "system", - content: `Automatic relay reached the ${maxAgentHops}-hop limit. Waiting for human input.`, + content: hopLimitHit + ? `Automatic relay reached the ${maxAgentHops}-hop limit. Waiting for human input.` + : `Automatic relay reached the ${maxAgentHops}-wake limit for this round (${usedRelays} used, ${newRelayTargets.length} requested). Waiting for human input.`, mentionedMemberIds: [], hopCount: hop, }); } - const saved = await this.#save(room); + let saved = await this.#save(room); if (breaker) { this.#interruptRelays(room.roomId); } if (!relayAllowed || breaker) targets = []; + // Re-evaluate pending membership synchronously after all awaits so the charged budget + // matches the exact set of newly enqueued wakes even if a queued wake was claimed mid-await. + // If a mid-await claim pushed newly requested wakes past maxAgentHops, trip the same breaker + // transition (pause room, interrupt relays, and append the limit notice) instead of dropping + // targets silently. + if (sender && targets.length > 0 && maxAgentHops > 0) { + const currentUsed = this.#relayBudgets.get(budgetKey) ?? 0; + const remainingBudget = Math.max(0, maxAgentHops - currentUsed); + const actualNewTargets = targets.filter( + (member) => + !this.#pending.get(member.threadId)?.has(roomMemberKey(room.roomId, member.memberId)), + ); + if (actualNewTargets.length > remainingBudget) { + targets = []; + this.#pausingRelayRooms.add(room.roomId); + room.relayPaused = true; + try { + await this.#append(room, { + senderType: "system", + content: `Automatic relay reached the ${maxAgentHops}-wake limit for this round (${currentUsed} used, ${actualNewTargets.length} requested). Waiting for human input.`, + mentionedMemberIds: [], + hopCount: hop, + }); + saved = await this.#save(room); + this.#interruptRelays(room.roomId); + } catch (error) { + this.#pausingRelayRooms.delete(room.roomId); + this.#wakeRoomPendingThreads(room.roomId); + throw error; + } + this.#pausingRelayRooms.delete(room.roomId); + } else if (actualNewTargets.length > 0) { + this.#recordRelayBudget(budgetKey, currentUsed + actualNewTargets.length); + } + } + const sameFlightRoomAndMember = + matchingFlight !== undefined && + wake?.roomId === room.roomId && + wake?.memberId === sender?.memberId; + if (publishOptions?.viaCli && sameFlightRoomAndMember) { + matchingFlight.cliPostedContents.push( + normalizeComparableGroupText(content, room.members, sender?.memberId), + ); + for (const member of targets) { + matchingFlight.cliAwakenedMemberIds.add(member.memberId); + } + } for (const member of targets) this.#enqueue(member.threadId, { roomId: room.roomId, @@ -1485,6 +1727,7 @@ export class GroupRoomHost { epoch, hop: sender ? hop + 1 : 0, relayGeneration, + triggerSeq: message.seq, }); return { room: saved, message, awakenedMemberIds: targets.map((m) => m.memberId) }; } @@ -1493,6 +1736,10 @@ export class GroupRoomHost { const activities: GroupMemberActivity[] = []; for (const member of room.members) { if (member.status === "removed") continue; + if (this.options.isBlocked?.(member.threadId)) { + activities.push({ memberId: member.memberId, state: "blocked" }); + continue; + } if (this.#flights.has(member.threadId) || this.options.activeTurn(member.threadId)) { activities.push({ memberId: member.memberId, state: "working" }); continue; @@ -1522,8 +1769,22 @@ export class GroupRoomHost { const wakes = this.#pending.get(threadId) ?? new Map(); const key = wakeKey(wake); const old = wakes.get(key); - if (!old || this.#preferWake(wake, old)) { + if (!old) { wakes.set(key, wake); + } else { + const winner = this.#preferWake(wake, old) ? wake : old; + const mergedTriggerSeq = + winner.triggerSeq === undefined + ? undefined + : old.triggerSeq === undefined + ? wake.triggerSeq + : wake.triggerSeq === undefined + ? old.triggerSeq + : Math.max(old.triggerSeq, wake.triggerSeq); + wakes.set(key, { + ...winner, + ...(mergedTriggerSeq !== undefined ? { triggerSeq: mergedTriggerSeq } : {}), + }); } this.#pending.set(threadId, wakes); } @@ -1597,6 +1858,18 @@ export class GroupRoomHost { return null; } const { room, member } = target; + if (wake.hop > 0 && this.options.isBlocked?.(threadId)) { + wakes.delete(key); + return null; + } + if ( + wake.hop > 0 && + wake.triggerSeq !== undefined && + member.lastDeliveredSeq >= wake.triggerSeq + ) { + wakes.delete(key); + return null; + } await this.#pendingCompactionSync; if (!this.#compactionIndexLoaded && this.#unresolvedCompactions.size > 0) { await this.#ensureCompactionIndex(); @@ -1607,6 +1880,24 @@ export class GroupRoomHost { const { messages } = await this.options.store.readGroupMessages(wake.roomId, { fromSeq: member.lastDeliveredSeq + 1, }); + let latestSelfSeq = 0; + let latestUnreadOtherSeq = 0; + for (const msg of messages) { + if (msg.senderType === "system") continue; + if (msg.senderThreadId === member.threadId || msg.senderMemberId === member.memberId) { + if (msg.seq > latestSelfSeq) latestSelfSeq = msg.seq; + } else if (msg.seq > latestUnreadOtherSeq) { + latestUnreadOtherSeq = msg.seq; + } + } + const supersededBySelfSeq = + wake.hop > 0 && + wake.triggerSeq !== undefined && + latestSelfSeq > 0 && + latestUnreadOtherSeq > 0 && + latestUnreadOtherSeq < latestSelfSeq + ? latestSelfSeq + : undefined; let activeRoom = room; let activeMember = member; let memoryContent: string | undefined; @@ -1643,7 +1934,13 @@ export class GroupRoomHost { includeMemory, forceRules: compacted, activities: this.#roomActivities(activeRoom), + ...(supersededBySelfSeq !== undefined ? { supersededBySelfSeq } : {}), }); + const needsMetadataSync = compacted || activeMember.lastRosterVersion === 0; + if (packed.unreadMessageCount === 0 && !needsMetadataSync) { + wakes.delete(key); + return null; + } const memoryDelivered = !memoryUnavailable && packed.memoryDelivered; return { room: activeRoom, @@ -1667,14 +1964,28 @@ export class GroupRoomHost { previousDeliveredSeq: prepared.member.lastDeliveredSeq, startedAtMs: performance.now(), early: new Map(), + cliPostedContents: [], + cliAwakenedMemberIds: new Set(), }; this.#flights.set(threadId, flight); // Claim only at the native send boundary. New posts can cancel or coalesce until then. let claimed = false; + let claimedStopGeneration = this.#stopGeneration(wake.roomId); const claimWake = () => { - if (this.#closed || this.#handoffPausedThreads.has(threadId) || wakes.get(key) !== wake) { + if ( + this.#closed || + this.#handoffPausedThreads.has(threadId) || + this.#stoppingRooms.has(wake.roomId) || + (wake.hop > 0 && this.#pausingRelayRooms.has(wake.roomId)) || + wakes.get(key) !== wake + ) { + return false; + } + if (wake.hop > 0 && this.options.isBlocked?.(threadId)) { + wakes.delete(key); return false; } + claimedStopGeneration = this.#stopGeneration(wake.roomId); if (wake.hop === 0) { flight.wake.relayGeneration = this.#relayGeneration(wake.roomId); } @@ -1722,6 +2033,7 @@ export class GroupRoomHost { if (error instanceof DelegationControlError && error.code === "THREAD_BUSY") { if (claimed) await this.#lock(wake.roomId, async () => { + if (this.#stopGeneration(wake.roomId) !== claimedStopGeneration) return; const requeued = wake.hop === 0 ? { ...wake, relayGeneration: this.#relayGeneration(wake.roomId) } @@ -1786,7 +2098,25 @@ export class GroupRoomHost { const sender = room?.members.find( (m) => m.memberId === memberId && m.threadId === threadId && m.status !== "removed", ); - if (room && sender) await this.#publish(room, { roomId, content }, sender, flight, turnId); + if (!room || !sender) return; + if ( + flight.cliPostedContents.length > 0 && + flight.cliPostedContents.includes( + normalizeComparableGroupText(content, room.members, sender.memberId), + ) + ) { + return; + } + await this.#publish( + room, + { roomId, content }, + sender, + flight, + turnId, + flight.cliAwakenedMemberIds.size > 0 + ? { suppressMemberIds: flight.cliAwakenedMemberIds } + : undefined, + ); }); } } diff --git a/packages/host-runtime/src/group-room-requests.ts b/packages/host-runtime/src/group-room-requests.ts index d8350cff20..38857fb873 100644 --- a/packages/host-runtime/src/group-room-requests.ts +++ b/packages/host-runtime/src/group-room-requests.ts @@ -11,6 +11,7 @@ import { GROUPS_READ_MESSAGES_METHOD, GROUPS_REBIND_MEMBER_METHOD, GROUPS_REMOVE_MEMBER_METHOD, + GROUPS_STOP_METHOD, GROUPS_UPDATE_MEMBER_METHOD, GROUPS_UPDATE_MEMORY_METHOD, GROUPS_UPDATE_METHOD, @@ -25,6 +26,7 @@ import { groupsReadMessagesParamsSchema, groupsRebindMemberParamsSchema, groupsRemoveMemberParamsSchema, + groupsStopParamsSchema, groupsUpdateMemberParamsSchema, groupsUpdateMemoryParamsSchema, groupsUpdateParamsSchema, @@ -40,6 +42,7 @@ export type GroupRoomRpc = Pick< | "get" | "create" | "update" + | "stop" | "delete" | "addMember" | "removeMember" @@ -73,6 +76,7 @@ const handlers = { [GROUPS_UPDATE_METHOD]: endpoint(groupsUpdateParamsSchema, (groups, params) => groups.update(params), ), + [GROUPS_STOP_METHOD]: endpoint(groupsStopParamsSchema, (groups, params) => groups.stop(params)), [GROUPS_DELETE_METHOD]: endpoint(groupsDeleteParamsSchema, (groups, params) => groups.delete(params), ), diff --git a/packages/host-runtime/test/group-context-packer.test.ts b/packages/host-runtime/test/group-context-packer.test.ts index e7e1e055a4..63eeb37b02 100644 --- a/packages/host-runtime/test/group-context-packer.test.ts +++ b/packages/host-runtime/test/group-context-packer.test.ts @@ -1,4 +1,9 @@ -import { GROUP_CONTEXT_MAX_BYTES, parseGroupContextMessage } from "@codexhost/shared-contracts"; +import { + GROUP_CONTEXT_MAX_BYTES, + GROUP_NO_REPLY_MARKER, + GROUP_SINGLE_MESSAGE_MAX_BYTES, + parseGroupContextMessage, +} from "@codexhost/shared-contracts"; import { expect, it } from "vitest"; import { groupRosterFits, @@ -34,7 +39,9 @@ it("packs only unread public messages from other Threads and includes rules and expect(context).toContain('room="Room "<&>"'); expect(context).not.toContain("room_id="); expect(context).toContain("Public group chat: reply directly to the group."); - expect(context).toContain("Everyone you @mention in one message starts immediately in parallel."); + expect(context).toContain( + "Eligible teammates you @mention in one message can run in parallel (subject to busy queueing, blocked state, and the relay budget).", + ); expect(context).toContain("\n"); expect(context).toContain(''); expect(context).toContain( @@ -42,8 +49,9 @@ it("packs only unread public messages from other Threads and includes rules and ); expect(context).not.toMatch(/version=|mention=|harnessId=|threadId=|status=|self=/u); expect(context).toContain( - '<answer> & more', + '<answer> & more', ); + expect(context).toContain('you="pi"'); expect(context).not.toMatch(/removed|already read|own output|tool_call_id|reasoning_signature/u); const followUp = packGroupContext(room, { ...self, lastRosterVersion: 1 }, messages); @@ -64,11 +72,11 @@ it("parses slim and legacy group wake envelopes cleanly for Thread display", () ]); expect(parseGroupContextMessage(slim)).toEqual({ roomTitle: 'Design & "QA"', - you: "@pi", + you: "pi", hasOmittedEarlier: false, messages: [ { seq: 1, from: "user", senderType: "user", content: "first <raw>" }, - { seq: 2, from: "@reviewer", senderType: "agent", content: "@pi please check" }, + { seq: 2, from: "reviewer", senderType: "agent", content: "@pi please check" }, ], }); @@ -98,28 +106,45 @@ it("parses slim and legacy group wake envelopes cleanly for Thread display", () it("keeps the newest messages under the UTF-8 budget and indexes omitted history", () => { const self = groupMember("pi"); const room = groupRoom([self]); - const messages = ["一".repeat(5_000), "🌙".repeat(2_000), "latest"].map((text, i) => - groupMessage(room.roomId, i + 1, text), - ); + // Each message stays within GROUP_SINGLE_MESSAGE_MAX_BYTES, while 6 combined exceed GROUP_CONTEXT_MAX_BYTES. + const messages = [ + "一".repeat(1_200), + "二".repeat(1_200), + "三".repeat(1_200), + "四".repeat(1_200), + "🌙".repeat(900), + "latest", + ].map((text, i) => groupMessage(room.roomId, i + 1, text)); const context = packGroupContext(room, self, messages); expect(Buffer.byteLength(context)).toBeLessThanOrEqual(GROUP_CONTEXT_MAX_BYTES); expect(context).toContain( `Earlier messages (seq 1..1) omitted; run "$CODEXHOST_CLI_PATH" group read ${room.roomId} --from 1 --to 1 --format text`, ); expect(context).not.toContain('"); }); -it("truncates a single oversized latest message without splitting a UTF-8 character or XML escape", () => { +it("truncates oversized individual messages with a pull hint without splitting UTF-8 or XML escapes", () => { const self = groupMember("pi"); const room = groupRoom([self]); - const context = packGroupContext(room, self, [ - groupMessage(room.roomId, 99, "🌙<&".repeat(5_000)), + const packed = packGroupContextWithImages(room, self, [ + groupMessage(room.roomId, 98, "🌙<&".repeat(5_000)), + groupMessage(room.roomId, 99, "short follow-up"), ]); + const context = packed.context; + expect(packed.packedMessageCount).toBe(2); expect(Buffer.byteLength(context)).toBeLessThanOrEqual(GROUP_CONTEXT_MAX_BYTES); - expect(context).toContain("seq 1..99) omitted"); - expect(context).toMatch(/🌙<&(?:🌙(?:<)?)?… \[truncated\]<\/msg>/u); + expect(context).toContain( + `… [truncated; run "$CODEXHOST_CLI_PATH" group read ${room.roomId} --from 98 --to 98 --format text]`, + ); + expect(context).toContain('short follow-up'); + const msg98Match = /]*>[\s\S]*?<\/msg>\n/u.exec(context); + expect(msg98Match).not.toBeNull(); + expect(Buffer.byteLength(msg98Match![0], "utf8")).toBeLessThanOrEqual( + GROUP_SINGLE_MESSAGE_MAX_BYTES, + ); + expect(msg98Match![0]).toMatch(/🌙<&(?:🌙(?:<)?)?\n… \[truncated;/u); expect(context).not.toContain("�"); }); @@ -185,8 +210,9 @@ it("keeps attachment order within each message when selecting the latest images it("renders teammate activity, shared room memory, cleared memory, truncation, and forceRules", () => { const self = groupMember("pi", { lastRosterVersion: 1, lastMemoryVersion: 1 }); const eng = groupMember("eng", { displayName: "Engineer" }); + const rev = groupMember("rev", { displayName: "Reviewer" }); const qa = groupMember("qa", { displayName: "QA & Ops" }); - const room = groupRoom([self, eng, qa], { memoryVersion: 2 }); + const room = groupRoom([self, eng, rev, qa], { memoryVersion: 2 }); const messages = [groupMessage(room.roomId, 1, "check status")]; const withMemoryAndActivity = packGroupContextWithImages(room, self, messages, { @@ -194,22 +220,28 @@ it("renders teammate activity, shared room memory, cleared memory, truncation, a activities: [ { memberId: self.memberId, state: "working" }, { memberId: eng.memberId, state: "working" }, + { memberId: rev.memberId, state: "blocked" }, { memberId: qa.memberId, state: "queued" }, ], + supersededBySelfSeq: 5, }); + expect(withMemoryAndActivity.packedMessageCount).toBe(1); expect(withMemoryAndActivity.context).not.toContain("Public group chat:"); expect(withMemoryAndActivity.context).not.toContain(""); expect(withMemoryAndActivity.context).toContain( - "busy: @Engineer (working), @QA & Ops (queued)", + "busy: Engineer (working), Reviewer (blocked), QA & Ops (queued)", + ); + expect(withMemoryAndActivity.context).not.toContain("pi (working)"); + expect(withMemoryAndActivity.context).toContain( + `These messages arrived before your latest reply (seq 5). If your reply already covers them, output only ${GROUP_NO_REPLY_MARKER}.`, ); - expect(withMemoryAndActivity.context).not.toContain("@pi (working)"); expect(withMemoryAndActivity.context).toContain( '\n# Decisions\nUse <strict> & fast API\n', ); // Envelope parser still extracts the message cleanly when activity & memory tags are present. expect(parseGroupContextMessage(withMemoryAndActivity.context)).toMatchObject({ roomTitle: room.title, - you: "@pi", + you: "pi", messages: [{ seq: 1, from: "user", senderType: "user", content: "check status" }], }); @@ -316,6 +348,146 @@ it("gracefully omits instead of throwing when a near-full roster leav expect(deliveredLater.context).toContain('\n# Durable notes\n'); }); +it("keeps single unread messages within 4 KiB even when senderName expands past the cap", () => { + const self = groupMember("a", { displayName: "A", lastRosterVersion: 1 }); + const other = groupMember("b", { displayName: "B" }); + const room = groupRoom([self, other]); + const hugeSenderName = "&".repeat(900); // 4,500 bytes when XML-escaped + const longBody = "payload-line ".repeat(500); + const messages = [ + groupMessage(room.roomId, 1, longBody, { + senderType: "agent", + senderMemberId: other.memberId, + senderHandle: "b", + senderName: hugeSenderName, + senderThreadId: other.threadId, + }), + ]; + const packed = packGroupContextWithImages(room, self, messages); + const msgMatch = packed.context.match(/\n/); + expect(msgMatch).not.toBeNull(); + expect(Buffer.byteLength(msgMatch![0], "utf8")).toBeLessThanOrEqual( + GROUP_SINGLE_MESSAGE_MAX_BYTES, + ); + expect(msgMatch![0]).toContain("[truncated"); + expect(Buffer.byteLength(packed.context, "utf8")).toBeLessThanOrEqual(GROUP_CONTEXT_MAX_BYTES); +}); + +it("reserves budget for superseded-by-self note before allocating long room memory", () => { + const self = groupMember("a", { + displayName: "A", + lastRosterVersion: 1, + lastMemoryVersion: 2, + }); + const other = groupMember("b", { displayName: "B" }); + const room = groupRoom([self, other], { memoryVersion: 3 }); + const messages = [ + groupMessage(room.roomId, 2, "Earlier question", { + senderType: "agent", + senderMemberId: other.memberId, + senderHandle: "b", + senderName: "B", + senderThreadId: other.threadId, + hopCount: 1, + }), + ]; + const packed = packGroupContextWithImages(room, self, messages, { + memory: { version: 3, content: "durable-note ".repeat(3000) }, + includeMemory: true, + supersededBySelfSeq: 3, + }); + expect(packed.memoryDelivered).toBe(true); + expect(packed.context).toContain(''); + expect(packed.context).toContain("arrived before your latest reply (seq 3)"); + expect(packed.context).toContain(GROUP_NO_REPLY_MARKER); + expect(Buffer.byteLength(packed.context, "utf8")).toBeLessThanOrEqual(GROUP_CONTEXT_MAX_BYTES); +}); + +it("clips oversized senderName in overall-budget fallback when long memory fills available headroom", () => { + const self = groupMember("a", { + displayName: "A", + lastRosterVersion: 1, + lastMemoryVersion: 1, + }); + const other = groupMember("b", { displayName: "B" }); + const room = groupRoom([self, other], { memoryVersion: 2 }); + const messages = [ + groupMessage(room.roomId, 5, "Important update ".repeat(300), { + senderType: "agent", + senderMemberId: other.memberId, + senderHandle: "b", + senderName: "&".repeat(900), + senderThreadId: other.threadId, + }), + ]; + const packed = packGroupContextWithImages(room, self, messages, { + memory: { version: 2, content: "&".repeat(4096) }, + includeMemory: true, + }); + expect(packed.unreadMessageCount).toBe(1); + expect(packed.packedMessageCount).toBe(1); + expect(packed.context).toContain(' { + const self = groupMember("a", { displayName: "A", lastRosterVersion: 1 }); + const other = groupMember("b", { displayName: "B" }); + const room = groupRoom([self, other]); + const longText = "detailed-log-line ".repeat(400); // > 7 KiB + const messages = [ + groupMessage(room.roomId, 9, longText, { + senderType: "user", + attachments: [ + { + attachmentId: "web-file:att-file-1/report.pdf", + kind: "file", + name: "report.pdf", + path: "/tmp/uploads/report.pdf", + bytes: 2048, + }, + { + attachmentId: "web-img:att-img-1/screen.png", + kind: "image", + name: "screen.png", + path: "/tmp/uploads/screen.png", + bytes: 512, + }, + ], + }), + ]; + const packed = packGroupContextWithImages(room, self, messages); + const msgMatch = packed.context.match(/\n/); + expect(msgMatch).not.toBeNull(); + expect(Buffer.byteLength(msgMatch![0], "utf8")).toBeLessThanOrEqual( + GROUP_SINGLE_MESSAGE_MAX_BYTES, + ); + expect(msgMatch![0]).toContain(`group read ${room.roomId} --from 9 --to 9 --format json`); + expect(msgMatch![0]).toContain( + "[file: report.pdf path="/tmp/uploads/report.pdf" bytes="2048"]", + ); + expect(msgMatch![0]).toContain("[image: screen.png path="/tmp/uploads/screen.png"]"); + expect(packed.imagePaths).toEqual(["/tmp/uploads/screen.png"]); + expect(Buffer.byteLength(packed.context, "utf8")).toBeLessThanOrEqual(GROUP_CONTEXT_MAX_BYTES); + + // Also verify overall-budget fallback retains the targeted --format json hint and attachment path. + const tightRoom = groupRoom([self, other], { memoryVersion: 2 }); + const tightPacked = packGroupContextWithImages(tightRoom, self, messages, { + memory: { version: 2, content: "M".repeat(15_000) }, + includeMemory: true, + }); + expect(tightPacked.packedMessageCount).toBe(1); + expect(tightPacked.context).toContain( + `group read ${tightRoom.roomId} --from 9 --to 9 --format json`, + ); + expect(tightPacked.context).toContain("report.pdf"); + expect(Buffer.byteLength(tightPacked.context, "utf8")).toBeLessThanOrEqual( + GROUP_CONTEXT_MAX_BYTES, + ); +}); + it("marks the group leader in and injects role-specific leader-mode guidance", () => { const lead = groupMember("lead", { displayName: "Architect", lastRosterVersion: 0 }); const worker = groupMember("worker", { displayName: "Engineer", lastRosterVersion: 0 }); diff --git a/packages/host-runtime/test/group-room-host.test.ts b/packages/host-runtime/test/group-room-host.test.ts index 8400c3ed2c..2c021516f3 100644 --- a/packages/host-runtime/test/group-room-host.test.ts +++ b/packages/host-runtime/test/group-room-host.test.ts @@ -25,6 +25,7 @@ import { GROUPS_READ_MESSAGES_METHOD, GROUPS_REBIND_MEMBER_METHOD, GROUPS_REMOVE_MEMBER_METHOD, + GROUPS_STOP_METHOD, GROUPS_UPDATE_MEMBER_METHOD, GROUPS_UPDATE_MEMORY_METHOD, GROUPS_UPDATE_METHOD, @@ -43,6 +44,7 @@ import { groupsReadMemoryResultSchema, groupsReadMessagesResultSchema, groupsRebindMemberResultSchema, + groupsStopResultSchema, groupsUpdateMemberResultSchema, groupsUpdateMemoryResultSchema, groupsUpdateResultSchema, @@ -58,6 +60,7 @@ import { type JsonObject, } from "@codexhost/shared-contracts"; import { afterEach, expect, it, vi } from "vitest"; +import { DelegationControlError } from "../src/delegation-types.js"; import { findEnclosingDotGit, startWithDelegationWorktree } from "../src/delegation-worktree.js"; import { GroupRoomHost } from "../src/group-room-host.js"; import { FakeHarnessAdapter } from "@codexhost/harness-adapter/testing"; @@ -1465,7 +1468,7 @@ it("queues explicit agent-to-agent mentions to busy teammates via busy-turn coal const cSnap = await fixture.adapter.sessions[2]!.readSnapshot(); if (!cSnap.ok) throw new Error(cSnap.error.message); expect(cSnap.value.turns[0]?.input[0]?.text).toContain( - `busy: @${b!.displayName} (working)`, + `busy: ${b!.displayName} (working)`, ); // Finish @b's active turn: @b MUST receive the coalesced follow-up turn rather than silently dropping the mentions. @@ -2747,6 +2750,571 @@ it("retries full memory reconciliation and never injects unreconciled content un } }); +it("stops a room by pausing relays, clearing both hop-0 and hop>0 pending wakes, and blocking in-flight relays", async () => { + const { fixture, call, create, post, read, started, answer } = await setup(); + const { + roomId, + members: [a, b, c], + } = await create([ + { kind: "harness", harnessId: "pi", handle: "a" }, + { kind: "harness", harnessId: "pi", handle: "b" }, + { kind: "harness", harnessId: "pi", handle: "c" }, + ]); + + // Put @b and @c in active private turns so both human (hop-0) and agent (hop-1) wakes queue. + const busyB = await startPiTurn(fixture, b!.threadId); + expect(await started(b!.threadId)).toBe(busyB); + const busyC = await startPiTurn(fixture, c!.threadId, 3); + expect(await started(c!.threadId)).toBe(busyC); + + // Queue a hop-0 human wake on @b and a hop-1 agent relay on @c while both are busy. + await post(roomId, `${formatGroupMemberMentionLink("b", b!.memberId)} queued human task`); + await post(roomId, `${formatGroupMemberMentionLink("a", a!.memberId)} relay to c`); + const aFirstTurn = await started(a!.threadId); + await answer( + aFirstTurn, + 0, + `${formatGroupMemberMentionLink("c", c!.memberId)} queued agent relay`, + ); + await vi.waitFor(async () => + expect((await read(roomId)).at(-1)?.content).toContain("queued agent relay"), + ); + + // Start another in-flight turn on @a, then stop the room: clears both hop-0 (@b) and hop-1 (@c). + await post(roomId, `${formatGroupMemberMentionLink("a", a!.memberId)} work in flight`); + const aTurn = await started(a!.threadId, aFirstTurn); + const stopResult = groupsStopResultSchema.parse(await call(GROUPS_STOP_METHOD, { roomId })); + expect(stopResult.room.relayPaused).toBe(true); + expect(new Set(stopResult.clearedPendingMemberIds)).toEqual(new Set([b!.memberId, c!.memberId])); + + // Even if @a finishes after stop and mentions @c, its pre-stop relay must be blocked. + await answer( + aTurn, + 0, + `${formatGroupMemberMentionLink("c", c!.memberId)} stale relay after stop`, + ); + await vi.waitFor(async () => + expect((await read(roomId)).at(-1)?.content).toContain("stale relay after stop"), + ); + + // Finish private turns on @b and @c: neither queued hop-0 wake nor pre-stop relay launches. + await answer(busyB, 1, "private b done"); + await answer(busyC, 2, "private c done"); + await new Promise((resolve) => setTimeout(resolve, 60)); + + const bSnap = await fixture.adapter.sessions[1]!.readSnapshot(); + const cSnap = await fixture.adapter.sessions[2]!.readSnapshot(); + if (!bSnap.ok || !cSnap.ok) throw new Error("Failed reading snapshots"); + expect(bSnap.value.turns).toHaveLength(1); + expect(cSnap.value.turns).toHaveLength(1); + + // Next human message cleanly resumes the room. + const resumed = await post( + roomId, + `${formatGroupMemberMentionLink("b", b!.memberId)} fresh task`, + ); + expect(resumed.room.relayPaused).toBe(false); + const bFreshTurn = await started(b!.threadId, busyB); + await answer(bFreshTurn, 1, "fresh task done"); +}); + +it("enforces custom maxAgentHops as a per-epoch total relay wake budget to curb fan-out amplification", async () => { + const { fixture, create, post, read, started, answer } = await setup(); + const { + roomId, + members: [a, b, c, d], + } = await create( + [ + { kind: "harness", harnessId: "pi", handle: "a" }, + { kind: "harness", harnessId: "pi", handle: "b" }, + { kind: "harness", harnessId: "pi", handle: "c" }, + { kind: "harness", harnessId: "pi", handle: "d" }, + ], + { maxAgentHops: 3 }, + ); + + // Human kicks off @a (hop 0). @a fans out to @b and @c (2 wakes used out of 3). + await post(roomId, `${formatGroupMemberMentionLink("a", a!.memberId)} start fan-out`); + const aTurn = await started(a!.threadId); + await answer( + aTurn, + 0, + `${formatGroupMemberMentionLink("b", b!.memberId)} ${formatGroupMemberMentionLink("c", c!.memberId)} split work`, + ); + const bTurn = await started(b!.threadId); + const cTurn = await started(c!.threadId); + + // @b (hop 1 < 3) tries to fan out to @a and @d (+2 new wakes -> 2 + 2 = 4 > 3): trips budget breaker! + await answer( + bTurn, + 1, + `${formatGroupMemberMentionLink("a", a!.memberId)} ${formatGroupMemberMentionLink("d", d!.memberId)} fan-out again`, + ); + await vi.waitFor(async () => { + const messages = await read(roomId); + expect(messages.at(-1)).toMatchObject({ + senderType: "system", + content: expect.stringContaining("3-wake limit"), + }); + }); + + // @c finishes after the breaker tripped and tries to mention @d: must stay blocked. + await answer(cTurn, 2, `${formatGroupMemberMentionLink("d", d!.memberId)} late relay`); + await vi.waitFor(async () => { + const messages = await read(roomId); + expect( + messages.some((m) => m.senderMemberId === c!.memberId && m.content.includes("late relay")), + ).toBe(true); + }); + await new Promise((resolve) => setTimeout(resolve, 50)); + const messages = await read(roomId); + expect(messages.some((m) => m.senderMemberId === d!.memberId)).toBe(false); + const dSnapshot = await fixture.adapter.sessions[3]!.readSnapshot(); + if (!dSnapshot.ok) throw new Error(dSnapshot.error.message); + expect(dSnapshot.value.turns).toHaveLength(0); +}); + +it("suppresses relays to blocked teammates, skips zero-unread wakes, and warns on superseded busy wakes", async () => { + const fixture = createFixture(); + fixtures.push(fixture); + await fixture.ready; + + const activeTurns = new Map(); + const blockedThreads = new Set(); + const delivered: Array<{ threadId: string; context: string; turnId: string }> = []; + let seqTurn = 0; + + const host = new GroupRoomHost({ + store: fixture.mappingStore, + getRole: async () => null, + getThread: async () => null, + createThread: async ({ harnessId }) => ({ + threadId: hostThreadIdSchema.parse(`thread-${++seqTurn}-${harnessId}`), + }), + startTurn: async (threadId, context, claimWake) => { + if (!claimWake()) return null; + const turnId = `turn-${++seqTurn}`; + activeTurns.set(threadId, turnId); + delivered.push({ threadId, context, turnId }); + return turnId; + }, + activeTurn: (threadId) => activeTurns.get(threadId), + isBlocked: (threadId) => blockedThreads.has(threadId), + changed: () => {}, + diagnose: () => {}, + }); + + try { + const { room } = await host.create({ + defaultCwd: "/synthetic", + members: [ + { kind: "harness", harnessId: "pi", handle: "a", displayName: "Alpha" }, + { kind: "harness", harnessId: "pi", handle: "b", displayName: "Beta" }, + { kind: "harness", harnessId: "pi", handle: "c", displayName: "Gamma" }, + ], + }); + const [a, b, c] = room.members; + + // 1. Mark Beta as blocked (pending approval/question): Alpha sees (blocked) and cannot auto-wake Beta. + blockedThreads.add(b!.threadId); + await host.post({ + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Alpha", a!.memberId)} ${formatGroupMemberMentionLink("Gamma", c!.memberId)} start`, + }); + await vi.waitFor(() => expect(delivered).toHaveLength(2)); + const aFirst = delivered.find((d) => d.threadId === a!.threadId)!; + const cFirst = delivered.find((d) => d.threadId === c!.threadId)!; + expect(aFirst.context).toContain("busy: Beta (blocked), Gamma ("); + + // Alpha mentions blocked Beta and working Gamma: Beta is suppressed, Gamma queues. + activeTurns.delete(a!.threadId); + host.turnCompleted( + a!.threadId, + aFirst.turnId, + () => + `${formatGroupMemberMentionLink("Beta", b!.memberId)} ${formatGroupMemberMentionLink("Gamma", c!.memberId)} check in`, + ); + await vi.waitFor(async () => + expect( + (await host.read({ roomId: room.roomId })).messages.some((m) => m.senderHandle === "a"), + ).toBe(true), + ); + expect(delivered.some((d) => d.threadId === b!.threadId)).toBe(false); + + // 2. Gamma finishes its initial turn (publishing seq after Alpha's mention). Gamma's queued + // follow-up wakes with the superseded-by-self-reply note so it can cleanly emit [[NO_REPLY]]. + activeTurns.delete(c!.threadId); + host.turnCompleted(c!.threadId, cFirst.turnId, () => "Gamma already handled it"); + await vi.waitFor(() => + expect(delivered.filter((d) => d.threadId === c!.threadId)).toHaveLength(2), + ); + const cSecond = delivered.filter((d) => d.threadId === c!.threadId)[1]!; + expect(cSecond.context).toContain( + `These messages arrived before your latest reply (seq 3). If your reply already covers them, output only ${GROUP_NO_REPLY_MARKER}.`, + ); + + // 3. Complete cSecond silently with a fenced/punctuated [[NO_REPLY]] and ensure Beta stays unwoken. + activeTurns.delete(c!.threadId); + host.turnCompleted( + c!.threadId, + cSecond.turnId, + () => `\`\`\`\n${GROUP_NO_REPLY_MARKER}.\n\`\`\``, + ); + await new Promise((resolve) => setTimeout(resolve, 40)); + + // 4. Zero-Unread & Already-Delivered Guard: + // Queue a hop-1 relay to busy Alpha, then simulate Alpha already having received that seq + // before draining -> #drain skips startTurn with zero extra turns. + activeTurns.set(a!.threadId, "private-busy-alpha"); + blockedThreads.delete(b!.threadId); + await host.post({ + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Gamma", c!.memberId)} ping alpha`, + }); + await vi.waitFor(() => + expect(delivered.filter((d) => d.threadId === c!.threadId)).toHaveLength(3), + ); + const cThird = delivered.filter((d) => d.threadId === c!.threadId)[2]!; + activeTurns.delete(c!.threadId); + host.turnCompleted( + c!.threadId, + cThird.turnId, + () => `${formatGroupMemberMentionLink("Alpha", a!.memberId)} already delivered check`, + ); + await vi.waitFor(async () => + expect((await host.read({ roomId: room.roomId })).messages.at(-1)?.content).toContain( + "already delivered check", + ), + ); + const snapshotBeforeDrain = (await host.get({ roomId: room.roomId })).room!; + const alphaEntry = snapshotBeforeDrain.members.find((m) => m.memberId === a!.memberId)!; + alphaEntry.lastDeliveredSeq = snapshotBeforeDrain.lastSeq; + await fixture.mappingStore.saveGroupRoom(snapshotBeforeDrain); + const deliveredBeforeSkip = delivered.length; + activeTurns.delete(a!.threadId); + host.threadIdle(a!.threadId); + await new Promise((resolve) => setTimeout(resolve, 40)); + expect(delivered.length).toBe(deliveredBeforeSkip); + + // 5. No-reply directive in prose suppresses downstream @mention relay without dropping the post. + const postRes = await host.post({ + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Alpha", a!.memberId)} status`, + }); + expect(postRes.awakenedMemberIds).toEqual([a!.memberId]); + await vi.waitFor(() => expect(delivered.length).toBe(deliveredBeforeSkip + 1)); + const aRead = delivered.at(-1)!; + activeTurns.delete(a!.threadId); + const beforeDirective = delivered.length; + host.turnCompleted( + a!.threadId, + aRead.turnId, + () => + `Holding off for ${formatGroupMemberMentionLink("Gamma", c!.memberId)}.\n${GROUP_NO_REPLY_MARKER}`, + ); + await vi.waitFor(async () => + expect((await host.read({ roomId: room.roomId })).messages.at(-1)?.content).toContain( + GROUP_NO_REPLY_MARKER, + ), + ); + await new Promise((resolve) => setTimeout(resolve, 40)); + expect(delivered.length).toBe(beforeDirective); + } finally { + host.close(); + } +}); + +it("deduplicates CLI group post and final turn completion within the same turn", async () => { + const fixture = createFixture(); + fixtures.push(fixture); + await fixture.ready; + + const activeTurns = new Map(); + const knownThreads = new Map< + string, + { + threadId: ReturnType; + harnessId: ReturnType; + } + >(); + const delivered: Array<{ threadId: string; context: string; turnId: string }> = []; + let seqTurn = 0; + + const host = new GroupRoomHost({ + store: fixture.mappingStore, + getRole: async () => null, + getThread: async (threadId) => knownThreads.get(threadId) ?? null, + createThread: async ({ harnessId }) => { + const threadId = hostThreadIdSchema.parse(`thread-cli-${++seqTurn}-${harnessId}`); + knownThreads.set(threadId, { threadId, harnessId }); + return { threadId }; + }, + startTurn: async (threadId, context, claimWake) => { + if (!claimWake()) return null; + const turnId = `turn-cli-${++seqTurn}`; + activeTurns.set(threadId, turnId); + delivered.push({ threadId, context, turnId }); + return turnId; + }, + activeTurn: (threadId) => activeTurns.get(threadId), + changed: () => {}, + diagnose: () => {}, + }); + + try { + const { room } = await host.create({ + defaultCwd: "/synthetic", + members: [ + { kind: "harness", harnessId: "pi", handle: "a", displayName: "Alpha" }, + { kind: "harness", harnessId: "pi", handle: "b", displayName: "Beta" }, + ], + }); + const [a, b] = room.members; + + // Case 1: Same content posted via CLI and returned at turn completion -> only one post, one wake. + await host.post({ + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Alpha", a!.memberId)} hand off to Beta`, + }); + await vi.waitFor(() => expect(delivered).toHaveLength(1)); + const aTurn1 = delivered[0]!; + await host.postFromCli( + { roomId: room.roomId, content: "@Beta please review PR 1" }, + ["b"], + a!.threadId, + ); + await vi.waitFor(() => expect(delivered).toHaveLength(2)); + const bTurn1 = delivered[1]!; + + activeTurns.delete(a!.threadId); + host.turnCompleted(a!.threadId, aTurn1.turnId, () => "@Beta please review PR 1"); + await new Promise((resolve) => setTimeout(resolve, 40)); + const afterSameText = (await host.read({ roomId: room.roomId })).messages; + expect(afterSameText.filter((m) => m.senderHandle === "a")).toHaveLength(1); + // Finish bTurn1: no queued duplicate wake for Beta. + activeTurns.delete(b!.threadId); + host.turnCompleted(b!.threadId, bTurn1.turnId, () => GROUP_NO_REPLY_MARKER); + await new Promise((resolve) => setTimeout(resolve, 40)); + expect(delivered.filter((d) => d.threadId === b!.threadId)).toHaveLength(1); + + // Case 2: Different final wrap-up text mentioning the same teammate already woken via CLI -> + // posts the wrap-up note but suppresses duplicate wake to Beta. + await host.post({ + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Alpha", a!.memberId)} second handoff`, + }); + await vi.waitFor(() => + expect(delivered.filter((d) => d.threadId === a!.threadId)).toHaveLength(2), + ); + const aTurn2 = delivered.filter((d) => d.threadId === a!.threadId)[1]!; + await host.postFromCli( + { roomId: room.roomId, content: "@Beta please check commit 2" }, + ["b"], + a!.threadId, + ); + await vi.waitFor(() => + expect(delivered.filter((d) => d.threadId === b!.threadId)).toHaveLength(2), + ); + const bTurn2 = delivered.filter((d) => d.threadId === b!.threadId)[1]!; + activeTurns.delete(a!.threadId); + host.turnCompleted( + a!.threadId, + aTurn2.turnId, + () => `Done — I already handed this off to @Beta in the group.`, + ); + await vi.waitFor(async () => + expect((await host.read({ roomId: room.roomId })).messages.at(-1)?.content).toContain( + "already handed this off", + ), + ); + // Finish bTurn2: Beta must NOT receive a 3rd turn from Alpha's wrap-up summary. + activeTurns.delete(b!.threadId); + host.turnCompleted(b!.threadId, bTurn2.turnId, () => GROUP_NO_REPLY_MARKER); + await new Promise((resolve) => setTimeout(resolve, 40)); + expect(delivered.filter((d) => d.threadId === b!.threadId)).toHaveLength(2); + + // Case 3: Preserve internal whitespace in code when comparing CLI post vs final turn text. + await host.post({ + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Alpha", a!.memberId)} check printf snippet`, + }); + await vi.waitFor(() => + expect(delivered.filter((d) => d.threadId === a!.threadId)).toHaveLength(3), + ); + const aTurn3 = delivered.filter((d) => d.threadId === a!.threadId)[2]!; + await host.postFromCli({ roomId: room.roomId, content: "printf 'a b'" }, [], a!.threadId); + activeTurns.delete(a!.threadId); + host.turnCompleted(a!.threadId, aTurn3.turnId, () => "printf 'a b'"); + await vi.waitFor(async () => + expect((await host.read({ roomId: room.roomId })).messages.at(-1)?.content).toBe( + "printf 'a b'", + ), + ); + + // Case 4: CLI post to Room B during Room A's turn must not suppress Room A's completion post. + const { room: roomB } = await host.create({ + defaultCwd: "/synthetic", + members: [{ kind: "existing", threadId: a!.threadId, handle: "a", displayName: "Alpha" }], + }); + await host.post({ + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Alpha", a!.memberId)} finish room A`, + }); + await vi.waitFor(() => + expect(delivered.filter((d) => d.threadId === a!.threadId)).toHaveLength(4), + ); + const aTurn4 = delivered.filter((d) => d.threadId === a!.threadId)[3]!; + await host.postFromCli({ roomId: roomB.roomId, content: "Done" }, [], a!.threadId); + activeTurns.delete(a!.threadId); + host.turnCompleted(a!.threadId, aTurn4.turnId, () => "Done"); + await vi.waitFor(async () => + expect((await host.read({ roomId: room.roomId })).messages.at(-1)?.content).toBe("Done"), + ); + } finally { + host.close(); + } +}); + +it("drops pre-stop claimed human wakes on THREAD_BUSY and re-checks relay budget after awaits", async () => { + const fixture = createFixture(); + fixtures.push(fixture); + await fixture.ready; + + const activeTurns = new Map(); + const delivered: Array<{ threadId: string; turnId: string }> = []; + let seqTurn = 0; + let releaseBusyStart: (() => void) | null = null; + let busyMode = false; + let holdBetaClaim: (() => void) | null = null; + let betaWaitingToClaim = false; + let betaClaimed = false; + let betaThreadId: string | null = null; + + const host = new GroupRoomHost({ + store: fixture.mappingStore, + getRole: async () => null, + getThread: async () => null, + createThread: async ({ harnessId }) => ({ + threadId: hostThreadIdSchema.parse(`thread-race-${++seqTurn}-${harnessId}`), + }), + startTurn: async (threadId, _context, claimWake) => { + if (betaThreadId === threadId && betaWaitingToClaim) { + await new Promise((resolve) => { + holdBetaClaim = resolve; + }); + betaWaitingToClaim = false; + if (!claimWake()) return null; + betaClaimed = true; + const turnId = `turn-race-${++seqTurn}`; + activeTurns.set(threadId, turnId); + delivered.push({ threadId, turnId }); + return turnId; + } + if (!claimWake()) return null; + if (busyMode) { + await new Promise((resolve) => { + releaseBusyStart = resolve; + }); + throw new DelegationControlError("THREAD_BUSY", "session busy"); + } + const turnId = `turn-race-${++seqTurn}`; + activeTurns.set(threadId, turnId); + delivered.push({ threadId, turnId }); + return turnId; + }, + activeTurn: (threadId) => activeTurns.get(threadId), + changed: () => {}, + diagnose: () => {}, + }); + + try { + const { room } = await host.create({ + defaultCwd: "/synthetic", + maxAgentHops: 2, + members: [ + { kind: "harness", harnessId: "pi", handle: "a", displayName: "Alpha" }, + { kind: "harness", harnessId: "pi", handle: "b", displayName: "Beta" }, + { kind: "harness", harnessId: "pi", handle: "c", displayName: "Gamma" }, + ], + }); + const [a, b, c] = room.members; + betaThreadId = b!.threadId; + + // 1. Human wake claimed before stop() returns THREAD_BUSY after stop() -> must NOT requeue. + busyMode = true; + await host.post({ + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Alpha", a!.memberId)} start work`, + }); + await vi.waitFor(() => expect(releaseBusyStart).not.toBeNull()); + await host.stop({ roomId: room.roomId }); + busyMode = false; + releaseBusyStart!(); + releaseBusyStart = null; + await new Promise((resolve) => setTimeout(resolve, 60)); + host.threadIdle(a!.threadId); + await new Promise((resolve) => setTimeout(resolve, 60)); + expect(delivered).toHaveLength(0); + + // 2. Budget re-check after #append/#save awaits: if a previously-pending wake is claimed while + // #publish awaits persistence, actual newly enqueued wakes must never exceed maxAgentHops (2). + await host.post({ + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Alpha", a!.memberId)} kick off`, + }); + await vi.waitFor(() => expect(delivered).toHaveLength(1)); + const aTurn = delivered[0]!; + // Let Beta's drain prepare and pause right before claimWake(), so Beta is still in #pending + // (1 of 2 budget used) when Alpha's second post starts, and claims mid-await inside saveGroupRoom. + betaWaitingToClaim = true; + await host.postFromCli( + { + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Beta", b!.memberId)} queued`, + }, + [], + a!.threadId, + ); + await vi.waitFor(() => expect(holdBetaClaim).not.toBeNull()); + + const origSave = fixture.mappingStore.saveGroupRoom.bind(fixture.mappingStore); + let intercepted = false; + vi.spyOn(fixture.mappingStore, "saveGroupRoom").mockImplementation(async (nextRoom) => { + const res = await origSave(nextRoom); + if (!intercepted && nextRoom.roomId === room.roomId) { + intercepted = true; + holdBetaClaim!(); + holdBetaClaim = null; + await vi.waitFor(() => expect(betaClaimed).toBe(true)); + } + return res; + }); + + // Alpha mentions both Beta (was pending before await, claimed during await) and Gamma (new). + // With 1/2 budget left and 2 newly requested wakes after await, #publish must trip the breaker: + // pause the room, append the wake-limit system notice, and wake nobody silently. + const secondCli = await host.postFromCli( + { + roomId: room.roomId, + content: `${formatGroupMemberMentionLink("Beta", b!.memberId)} ${formatGroupMemberMentionLink("Gamma", c!.memberId)} follow up`, + }, + [], + a!.threadId, + ); + expect(secondCli.awakenedMemberIds).toEqual([]); + expect(secondCli.room.relayPaused).toBe(true); + const msgsAfterMidAwaitBreak = (await host.read({ roomId: room.roomId })).messages; + expect(msgsAfterMidAwaitBreak.at(-1)).toMatchObject({ + senderType: "system", + content: expect.stringContaining("2-wake limit for this round"), + }); + activeTurns.delete(a!.threadId); + host.turnCompleted(a!.threadId, aTurn.turnId, () => GROUP_NO_REPLY_MARKER); + } finally { + host.close(); + } +}); + it("enforces optional leader mode: leader dispatches teammates, non-leaders can only wake leader, and switching/clearing works", async () => { const { fixture, call, create, post, read, started, answer } = await setup(); const created = await create( @@ -4586,3 +5154,558 @@ it("auto-initializes Git inside projectless group workspaces without climbing in rmSync(baseTmp, { recursive: true, force: true }); } }, 30_000); + +it("preserves memberId identity during CLI/turn dedup, serializes dedup inside room lock, protects active relay budgets from eviction, preserves wakes on failed stop/update saves, and rechecks isBlocked at claimWake", async () => { + const fixture = createFixture(); + fixtures.push(fixture); + await fixture.ready; + + const activeTurns = new Map(); + const blockedThreads = new Set(); + const delivered: Array<{ threadId: string; context: string; turnId: string }> = []; + let seqTurn = 0; + let beforeClaimWake: ((threadId: string) => void | Promise) | undefined; + let onClaimAttempt: ((threadId: string, claimed: boolean) => void) | undefined; + let onDelivered: (() => void) | undefined; + let failNextSave: string | null = null; + let holdNextCliSave: (() => void) | undefined; + let cliSaveEntered: (() => void) | undefined; + + const rawStore = fixture.mappingStore; + const memoryRooms = new Map[0]>(); + const memoryMessages = new Map< + string, + Array[0]> + >(); + let memoryOnlyRoomId: string | null = null; + const wrappedStore = { + listGroupRooms: async () => { + const diskRooms = await rawStore.listGroupRooms(); + return [...diskRooms, ...memoryRooms.values().map((r) => structuredClone(r))]; + }, + getGroupRoom: async (roomId: string) => { + const mem = memoryRooms.get(roomId); + if (mem) return structuredClone(mem); + return rawStore.getGroupRoom(roomId); + }, + saveGroupRoom: async (room: Parameters[0]) => { + if (failNextSave !== null) { + const message = failNextSave; + failNextSave = null; + throw new Error(message); + } + if (holdNextCliSave !== undefined) { + const release = holdNextCliSave; + holdNextCliSave = undefined; + cliSaveEntered?.(); + cliSaveEntered = undefined; + await new Promise((resolve) => { + holdNextCliSave = () => { + release(); + resolve(); + }; + }); + } + if (room.roomId === memoryOnlyRoomId || memoryRooms.has(room.roomId)) { + const cloned = structuredClone(room); + memoryRooms.set(room.roomId, cloned); + return structuredClone(cloned); + } + return rawStore.saveGroupRoom(room); + }, + deleteGroupRoom: async (roomId: string) => { + if (memoryRooms.delete(roomId)) { + memoryMessages.delete(roomId); + return true; + } + return rawStore.deleteGroupRoom(roomId); + }, + appendGroupMessage: async (msg: Parameters[0]) => { + if (msg.roomId === memoryOnlyRoomId || memoryRooms.has(msg.roomId)) { + const list = memoryMessages.get(msg.roomId) ?? []; + const cloned = structuredClone(msg); + list.push(cloned); + memoryMessages.set(msg.roomId, list); + return structuredClone(cloned); + } + return rawStore.appendGroupMessage(msg); + }, + readGroupMessages: async ( + roomId: string, + opts?: Parameters[1], + ) => { + if (roomId === memoryOnlyRoomId || memoryRooms.has(roomId)) { + const list = memoryMessages.get(roomId) ?? []; + const filtered = list.filter((m) => { + if (opts?.fromSeq !== undefined && m.seq < opts.fromSeq) return false; + if (opts?.toSeq !== undefined && m.seq > opts.toSeq) return false; + if (opts?.beforeSeq !== undefined && m.seq >= opts.beforeSeq) return false; + return true; + }); + const sliced = opts?.limit !== undefined ? filtered.slice(-opts.limit) : filtered; + return { + messages: sliced.map((m) => structuredClone(m)), + hasMore: sliced.length < filtered.length, + }; + } + return rawStore.readGroupMessages(roomId, opts); + }, + readGroupMemory: rawStore.readGroupMemory.bind(rawStore), + writeGroupMemory: rawStore.writeGroupMemory.bind(rawStore), + }; + + const host = new GroupRoomHost({ + store: wrappedStore, + getRole: async () => null, + getThread: async () => null, + createThread: async ({ harnessId }) => ({ + threadId: hostThreadIdSchema.parse(`thread-guard-${++seqTurn}-${harnessId}`), + }), + startTurn: async (threadId, context, claimWake) => { + await beforeClaimWake?.(threadId); + const claimed = claimWake(); + onClaimAttempt?.(threadId, claimed); + if (!claimed) return null; + const turnId = `turn-guard-${++seqTurn}`; + activeTurns.set(threadId, turnId); + delivered.push({ threadId, context, turnId }); + onDelivered?.(); + return turnId; + }, + activeTurn: (threadId) => activeTurns.get(threadId), + isBlocked: (threadId) => blockedThreads.has(threadId), + changed: () => {}, + diagnose: () => {}, + }); + + try { + // 1. Rename collision: CLI posts @Alice (member B), then B renames to Bob and C renames to Alice; + // turn completion mentioning @Alice now resolves to member C and must NOT be falsely deduplicated. + const { room: renameRoom } = await host.create({ + defaultCwd: "/synthetic", + members: [ + { kind: "harness", harnessId: "pi", handle: "a", displayName: "Alpha" }, + { kind: "harness", harnessId: "pi", handle: "b", displayName: "Alice" }, + { kind: "harness", harnessId: "pi", handle: "c", displayName: "Charlie" }, + ], + }); + const [a, b, c] = renameRoom.members; + await host.post({ + roomId: renameRoom.roomId, + content: `${formatGroupMemberMentionLink("Alpha", a!.memberId)} start`, + }); + await vi.waitFor(() => expect(delivered).toHaveLength(1)); + const aTurn = delivered[0]!.turnId; + + await host.postFromCli( + { roomId: renameRoom.roomId, content: "@Alice please check" }, + [], + a!.threadId, + ); + await host.updateMember({ + roomId: renameRoom.roomId, + memberId: b!.memberId, + displayName: "Bob", + }); + await host.updateMember({ + roomId: renameRoom.roomId, + memberId: c!.memberId, + displayName: "Alice", + }); + activeTurns.delete(a!.threadId); + host.turnCompleted(a!.threadId, aTurn, () => "@Alice please check"); + await vi.waitFor(async () => { + const msgs = (await host.read({ roomId: renameRoom.roomId })).messages; + expect(msgs.filter((m) => m.senderMemberId === a!.memberId)).toHaveLength(2); + }); + const renameMsgs = (await host.read({ roomId: renameRoom.roomId })).messages.filter( + (m) => m.senderMemberId === a!.memberId, + ); + expect(renameMsgs[0]!.mentionedMemberIds).toEqual([b!.memberId]); + expect(renameMsgs[1]!.mentionedMemberIds).toEqual([c!.memberId]); + + // Clean up active turns for b & c before next scenario. + await vi.waitFor(() => expect(delivered.length).toBeGreaterThanOrEqual(3)); + for (const m of [b!, c!]) { + const t = activeTurns.get(m.threadId); + activeTurns.delete(m.threadId); + if (t) host.turnCompleted(m.threadId, t, () => GROUP_NO_REPLY_MARKER); + } + + // 2. Concurrent CLI post & turnCompleted race: dedup runs inside the room lock so duplicates are prevented. + const { room: raceRoom } = await host.create({ + defaultCwd: "/synthetic", + members: [{ kind: "harness", harnessId: "pi", handle: "r1", displayName: "Racer" }], + }); + const [r1] = raceRoom.members; + const beforeRaceCount = delivered.length; + await host.post({ + roomId: raceRoom.roomId, + content: `${formatGroupMemberMentionLink("Racer", r1!.memberId)} race`, + }); + await vi.waitFor(() => expect(delivered).toHaveLength(beforeRaceCount + 1)); + const raceTurn = delivered.at(-1)!.turnId; + + let enteredResolve!: () => void; + const enteredPromise = new Promise((resolve) => { + enteredResolve = resolve; + }); + cliSaveEntered = enteredResolve; + holdNextCliSave = () => {}; + const cliPostPromise = host.postFromCli( + { roomId: raceRoom.roomId, content: "Exact same update" }, + [], + r1!.threadId, + ); + await enteredPromise; + // Turn finishes while CLI post is still holding the room lock inside saveGroupRoom. + activeTurns.delete(r1!.threadId); + host.turnCompleted(r1!.threadId, raceTurn, () => "Exact same update"); + await new Promise((resolve) => setTimeout(resolve, 25)); + const releaseCliSave = holdNextCliSave!; + holdNextCliSave = undefined; + releaseCliSave(); + await cliPostPromise; + await new Promise((resolve) => setTimeout(resolve, 30)); + const raceMsgs = (await host.read({ roomId: raceRoom.roomId })).messages.filter( + (m) => m.senderMemberId === r1!.memberId, + ); + expect(raceMsgs).toHaveLength(1); + + // 3. stop() and update({ relayPaused: true }) persistence failures must not drop queued wakes. + const { room: saveFailRoom } = await host.create({ + defaultCwd: "/synthetic", + members: [ + { kind: "harness", harnessId: "pi", handle: "s1", displayName: "S1" }, + { kind: "harness", harnessId: "pi", handle: "s2", displayName: "S2" }, + ], + }); + const [s1, s2] = saveFailRoom.members; + activeTurns.set(s1!.threadId, "busy-s1"); + await host.post({ + roomId: saveFailRoom.roomId, + content: `${formatGroupMemberMentionLink("S1", s1!.memberId)} queued task`, + }); + failNextSave = "disk full on stop"; + await expect(host.stop({ roomId: saveFailRoom.roomId })).rejects.toThrow("disk full on stop"); + const afterFailedStopRoom = (await host.get({ roomId: saveFailRoom.roomId })).room!; + expect(afterFailedStopRoom.relayPaused).toBe(false); + + // Releasing s1 must still deliver the preserved hop-0 human wake because stop() did not persist. + const beforeReleaseS1 = delivered.length; + activeTurns.delete(s1!.threadId); + host.threadIdle(s1!.threadId); + await vi.waitFor(() => expect(delivered).toHaveLength(beforeReleaseS1 + 1)); + expect(delivered.at(-1)!.threadId).toBe(s1!.threadId); + expect(delivered.at(-1)!.context).toContain("queued task"); + const s1Turn = delivered.at(-1)!.turnId; + + // Now actually enqueue a hop > 0 automatic relay to busy S2, then fail update({ relayPaused: true }). + activeTurns.set(s2!.threadId, "busy-s2"); + activeTurns.delete(s1!.threadId); + host.turnCompleted( + s1!.threadId, + s1Turn, + () => `${formatGroupMemberMentionLink("S2", s2!.memberId)} relay handoff for s2`, + ); + await vi.waitFor(async () => { + const msgs = (await host.read({ roomId: saveFailRoom.roomId })).messages; + expect(msgs.some((m) => m.content.includes("relay handoff for s2"))).toBe(true); + }); + failNextSave = "disk full on update"; + await expect(host.update({ roomId: saveFailRoom.roomId, relayPaused: true })).rejects.toThrow( + "disk full on update", + ); + + // Releasing s2 must still deliver the preserved hop-1 relay wake because update() did not persist. + const beforeReleaseS2 = delivered.length; + activeTurns.delete(s2!.threadId); + host.threadIdle(s2!.threadId); + await vi.waitFor(() => expect(delivered).toHaveLength(beforeReleaseS2 + 1)); + expect(delivered.at(-1)!.threadId).toBe(s2!.threadId); + expect(delivered.at(-1)!.context).toContain("relay handoff for s2"); + activeTurns.delete(s2!.threadId); + host.turnCompleted(s2!.threadId, delivered.at(-1)!.turnId, () => GROUP_NO_REPLY_MARKER); + + // 4. claimWake() rechecks isBlocked for hop > 0 relays right at the send boundary. + const { room: claimBlockRoom } = await host.create({ + defaultCwd: "/synthetic", + members: [ + { kind: "harness", harnessId: "pi", handle: "cb1", displayName: "CB1" }, + { kind: "harness", harnessId: "pi", handle: "cb2", displayName: "CB2" }, + ], + }); + const [cb1, cb2] = claimBlockRoom.members; + const beforeCb = delivered.length; + await host.post({ + roomId: claimBlockRoom.roomId, + content: `${formatGroupMemberMentionLink("CB1", cb1!.memberId)} kick off`, + }); + await vi.waitFor(() => expect(delivered).toHaveLength(beforeCb + 1)); + const cb1Turn = delivered.at(-1)!.turnId; + let cb2ClaimResult: boolean | undefined; + const cb2ClaimAttempted = new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error("Timed out waiting for CB2 claimWake attempt")), + 5_000, + ); + onClaimAttempt = (tid, claimed) => { + if (tid === cb2!.threadId) { + clearTimeout(timer); + cb2ClaimResult = claimed; + onClaimAttempt = undefined; + resolve(); + } + }; + }); + beforeClaimWake = (tid) => { + if (tid === cb2!.threadId) blockedThreads.add(tid); + }; + activeTurns.delete(cb1!.threadId); + host.turnCompleted( + cb1!.threadId, + cb1Turn, + () => `${formatGroupMemberMentionLink("CB2", cb2!.memberId)} handoff`, + ); + await cb2ClaimAttempted; + expect(cb2ClaimResult).toBe(false); + expect(delivered.some((d) => d.threadId === cb2!.threadId)).toBe(false); + beforeClaimWake = undefined; + blockedThreads.delete(cb2!.threadId); + + // 5. >512 relay budget rounds must never evict a budget key referenced by an active flight + // OR by a room's current (relayGeneration, humanEpoch) round still usable via CLI posts. + const { room: budgetRoom } = await host.create({ + defaultCwd: "/synthetic", + maxAgentHops: 2, + members: [ + { kind: "harness", harnessId: "pi", handle: "b1", displayName: "B1" }, + { kind: "harness", harnessId: "pi", handle: "b2", displayName: "B2" }, + { kind: "harness", harnessId: "pi", handle: "b3", displayName: "B3" }, + ], + }); + const [b1, b2, b3] = budgetRoom.members; + const beforeBudget = delivered.length; + await host.post({ + roomId: budgetRoom.roomId, + content: `${formatGroupMemberMentionLink("B1", b1!.memberId)} start protected epoch`, + }); + await vi.waitFor(() => expect(delivered).toHaveLength(beforeBudget + 1)); + const b1Turn = delivered.at(-1)!.turnId; + // B1 wakes B2 (uses 1 of 2 relay wakes in epoch 1). B2 stays active in flight! + activeTurns.delete(b1!.threadId); + host.turnCompleted( + b1!.threadId, + b1Turn, + () => `${formatGroupMemberMentionLink("B2", b2!.memberId)} step 1`, + ); + await vi.waitFor(() => expect(delivered).toHaveLength(beforeBudget + 2)); + const b2Turn = delivered.at(-1)!.turnId; + + // Also create a room whose current epoch budget (2/2) was consumed via CLI from a native + // non-group Turn, leaving NO active group flights or pending wakes. + const { room: cliBudgetRoom } = await host.create({ + defaultCwd: "/synthetic", + maxAgentHops: 2, + members: [ + { kind: "harness", harnessId: "pi", handle: "n1", displayName: "N1" }, + { kind: "harness", harnessId: "pi", handle: "n2", displayName: "N2" }, + ], + }); + const [n1, n2] = cliBudgetRoom.members; + activeTurns.set(n1!.threadId, "native-private-turn"); + for (let wakeIdx = 1; wakeIdx <= 2; wakeIdx++) { + const beforeCliWake = delivered.length; + await host.postFromCli( + { + roomId: cliBudgetRoom.roomId, + content: `${formatGroupMemberMentionLink("N2", n2!.memberId)} cli wake ${wakeIdx}`, + }, + [], + n1!.threadId, + ); + await vi.waitFor(() => expect(delivered).toHaveLength(beforeCliWake + 1)); + const n2Turn = delivered.at(-1)!.turnId; + activeTurns.delete(n2!.threadId); + host.turnCompleted(n2!.threadId, n2Turn, () => GROUP_NO_REPLY_MARKER); + await vi.waitFor(async () => { + const currentRoom = (await host.get({ roomId: cliBudgetRoom.roomId })).room!; + expect(currentRoom.lastSeq).toBe(wakeIdx); + }); + } + + // Generate >512 distinct budget keys in another room (backed in memory for fast LRU churn). + const { room: churnRoom } = await host.create({ + defaultCwd: "/synthetic", + maxAgentHops: 2, + members: [ + { kind: "harness", harnessId: "pi", handle: "c1", displayName: "C1" }, + { kind: "harness", harnessId: "pi", handle: "c2", displayName: "C2" }, + ], + }); + memoryOnlyRoomId = churnRoom.roomId; + memoryRooms.set(churnRoom.roomId, structuredClone(churnRoom)); + memoryMessages.set(churnRoom.roomId, []); + const [c1, c2] = churnRoom.members; + activeTurns.set(c1!.threadId, "churn-turn"); + for (let i = 0; i < 520; i++) { + await host.post({ roomId: churnRoom.roomId, content: `epoch ${i}` }); + const beforeChurn = delivered.length; + const deliveredNext = new Promise((resolve) => { + onDelivered = () => { + if (delivered.length >= beforeChurn + 1) { + onDelivered = undefined; + resolve(); + } + }; + }); + await host.postFromCli( + { + roomId: churnRoom.roomId, + content: `${formatGroupMemberMentionLink("C2", c2!.memberId)} ping ${i}`, + }, + [], + c1!.threadId, + ); + if (delivered.length < beforeChurn + 1) await deliveredNext; + onDelivered = undefined; + const c2Turn = delivered.at(-1)!.turnId; + activeTurns.delete(c2!.threadId); + host.turnCompleted(c2!.threadId, c2Turn, () => GROUP_NO_REPLY_MARKER); + } + + // Now B2 tries to fan out to both B1 and B3 (+2 new wakes -> 1 + 2 = 3 > maxAgentHops 2). + // Because B2's active flight budget key was protected from eviction, the breaker MUST trip! + activeTurns.delete(b2!.threadId); + host.turnCompleted( + b2!.threadId, + b2Turn, + () => + `${formatGroupMemberMentionLink("B1", b1!.memberId)} ${formatGroupMemberMentionLink("B3", b3!.memberId)} exceed budget`, + ); + await vi.waitFor(async () => { + const msgs = (await host.read({ roomId: budgetRoom.roomId })).messages; + expect( + msgs.some((m) => m.senderType === "system" && m.content.includes("2-wake limit")), + ).toBe(true); + }); + expect(delivered.some((d) => d.threadId === b3!.threadId)).toBe(false); + + // And in cliBudgetRoom (no active flights or pending wakes), N1's 3rd CLI mention in the + // same current epoch MUST still trip the 2-wake breaker because current-epoch keys are kept. + const cliThird = await host.postFromCli( + { + roomId: cliBudgetRoom.roomId, + content: `${formatGroupMemberMentionLink("N2", n2!.memberId)} cli wake 3 must trip`, + }, + [], + n1!.threadId, + ); + expect(cliThird.awakenedMemberIds).toEqual([]); + expect(cliThird.room.relayPaused).toBe(true); + const cliBudgetMsgs = (await host.read({ roomId: cliBudgetRoom.roomId })).messages; + expect( + cliBudgetMsgs.some((m) => m.senderType === "system" && m.content.includes("2-wake limit")), + ).toBe(true); + } finally { + host.close(); + } +}, 30_000); + +it("treats pending official Codex approval requests as blocked in standard Desktop mode and clears after resolution", async () => { + const { fixture, call, create, post, read, started, answer, nativeReply, nativeInitialize } = + await setup(); + await nativeInitialize(); + + const creating = create([ + { kind: "harness", harnessId: "pi", handle: "pi1", displayName: "Pi" }, + { + kind: "existing", + threadId: "official-approval-thread", + handle: "codex1", + displayName: "Codex", + }, + ]); + await nativeReply("thread/read", { + thread: { id: "official-approval-thread", preview: "existing", cwd: "/synthetic" }, + }); + const room = await creating; + const [piMember, codexMember] = room.members; + + // Native official process sends a commandExecution approval request for Codex's thread. + writeRequest(fixture.official.stdout, { + id: 777, + method: "item/commandExecution/requestApproval", + params: { + threadId: codexMember!.threadId, + turnId: "official-turn-1", + command: "rm -rf /tmp/demo", + }, + }); + const forwardedApproval = await fixture.collector.waitFor( + (msg) => msg.method === "item/commandExecution/requestApproval", + ); + const forwardedApprovalId = requiredMessageId(forwardedApproval); + + // Human wakes Pi: Pi's wake envelope should show Codex (blocked) in , + // and Pi's @Codex auto-relay must be suppressed while the approval is pending. + await post(room.roomId, `${formatGroupMemberMentionLink("Pi", piMember!.memberId)} check codex`); + const piTurn1 = await started(piMember!.threadId); + await answer( + piTurn1, + 0, + `${formatGroupMemberMentionLink("Codex", codexMember!.memberId)} please run`, + ); + const piSnap1 = await fixture.adapter.sessions[0]!.readSnapshot(); + if (!piSnap1.ok) throw new Error(piSnap1.error.message); + expect(piSnap1.value.turns[0]?.input[0]?.text ?? "").toContain( + "busy: Codex (blocked)", + ); + await vi.waitFor(async () => { + const msgs = await read(room.roomId); + expect(msgs.some((m) => m.content.includes("please run"))).toBe(true); + }); + // Acquire the room lock via a no-op room update to guarantee Pi's #complete/#publish + // critical section has fully finished before resolving the approval. + await call(GROUPS_UPDATE_METHOD, { roomId: room.roomId, pinned: false }); + expect(fixture.official.stdin.readableLength).toBe(0); + + // Desktop replies to the official approval request -> Codex is no longer blocked. + writeRequest(fixture.desktopInput, { + id: forwardedApprovalId, + result: { decision: "accept" }, + }); + const forwardedReply = await readJsonLine(fixture.official.stdin); + expect(forwardedReply).toEqual({ id: 777, result: { decision: "accept" } }); + + // Now a new Pi turn mentioning Codex wakes Codex normally (no longer listed as blocked). + await post(room.roomId, `${formatGroupMemberMentionLink("Pi", piMember!.memberId)} try again`); + const piTurn2 = await started(piMember!.threadId, piTurn1); + await answer( + piTurn2, + 0, + `${formatGroupMemberMentionLink("Codex", codexMember!.memberId)} now unblocked`, + ); + const piSnap2 = await fixture.adapter.sessions[0]!.readSnapshot(); + if (!piSnap2.ok) throw new Error(piSnap2.error.message); + expect(piSnap2.value.turns.at(-1)?.input[0]?.text ?? "").not.toContain("Codex (blocked)"); + + // Answer thread/resume if sent first, then verify turn/start is actually dispatched for the + // second ("now unblocked") mention rather than a stale wake from the first mention. + let nextOfficialReq = await readJsonLine(fixture.official.stdin); + if (nextOfficialReq.method === "thread/resume") { + expect(messageParams(nextOfficialReq)).toMatchObject({ threadId: codexMember!.threadId }); + writeRequest(fixture.official.stdout, { + id: requiredMessageId(nextOfficialReq), + result: { thread: { id: codexMember!.threadId, status: { type: "idle" } } }, + }); + nextOfficialReq = await readJsonLine(fixture.official.stdin); + } + expect(nextOfficialReq).toMatchObject({ + method: "turn/start", + params: { + threadId: codexMember!.threadId, + input: [{ type: "text", text: expect.stringContaining("now unblocked") }], + }, + }); +}); diff --git a/packages/renderer-extension/src/renderer-model-client.ts b/packages/renderer-extension/src/renderer-model-client.ts index dc1ecac6e4..13c88ca024 100644 --- a/packages/renderer-extension/src/renderer-model-client.ts +++ b/packages/renderer-extension/src/renderer-model-client.ts @@ -14,6 +14,7 @@ import { GROUPS_READ_MEMORY_METHOD, GROUPS_READ_MESSAGES_METHOD, GROUPS_REMOVE_MEMBER_METHOD, + GROUPS_STOP_METHOD, GROUPS_UPDATE_MEMBER_METHOD, GROUPS_UPDATE_MEMORY_METHOD, GROUPS_UPDATE_METHOD, @@ -1187,6 +1188,7 @@ const ALLOWED_DESKTOP_SURFACE_METHODS: ReadonlySet = new Set([ GROUPS_GET_METHOD, GROUPS_CREATE_METHOD, GROUPS_UPDATE_METHOD, + GROUPS_STOP_METHOD, GROUPS_DELETE_METHOD, GROUPS_ADD_MEMBER_METHOD, GROUPS_UPDATE_MEMBER_METHOD, diff --git a/packages/shared-contracts/src/client-channel.ts b/packages/shared-contracts/src/client-channel.ts index 81d05454af..032ee81118 100644 --- a/packages/shared-contracts/src/client-channel.ts +++ b/packages/shared-contracts/src/client-channel.ts @@ -27,6 +27,7 @@ import { GROUPS_READ_MESSAGES_METHOD, GROUPS_REBIND_MEMBER_METHOD, GROUPS_REMOVE_MEMBER_METHOD, + GROUPS_STOP_METHOD, GROUPS_UPDATE_MEMBER_METHOD, GROUPS_UPDATE_MEMORY_METHOD, GROUPS_UPDATE_METHOD, @@ -111,6 +112,7 @@ export const CLIENT_CHANNEL_METHODS = [ GROUPS_GET_METHOD, GROUPS_CREATE_METHOD, GROUPS_UPDATE_METHOD, + GROUPS_STOP_METHOD, GROUPS_DELETE_METHOD, GROUPS_ADD_MEMBER_METHOD, GROUPS_UPDATE_MEMBER_METHOD, diff --git a/packages/shared-contracts/src/group-chat.ts b/packages/shared-contracts/src/group-chat.ts index b3987fc7d4..424615ecaf 100644 --- a/packages/shared-contracts/src/group-chat.ts +++ b/packages/shared-contracts/src/group-chat.ts @@ -3,6 +3,7 @@ import { roleModelSchema, roleSlugSchema, threadRoleSnapshotSchema } from "./age import { harnessIdSchema, harnessThinkingOptionIdSchema, hostThreadIdSchema } from "./ids.js"; export const GROUP_CONTEXT_MAX_BYTES = 16_384; +export const GROUP_SINGLE_MESSAGE_MAX_BYTES = 4_096; export const GROUP_MEMORY_BYTES_PER_KB = 1_024; export const GROUP_MEMORY_MIN_BYTES = GROUP_MEMORY_BYTES_PER_KB; export const GROUP_MEMORY_MAX_BYTES = 4 * GROUP_MEMORY_BYTES_PER_KB; @@ -48,16 +49,47 @@ export function groupUtf8ByteLength(text: string): number { /** True when an Agent explicitly emits the protocol silence marker and nothing else. */ export function isGroupNoReply(text: string): boolean { - const trimmed = text.trim(); - if (trimmed === GROUP_NO_REPLY_MARKER) return true; - if ( - trimmed.length === GROUP_NO_REPLY_MARKER.length + 2 && - trimmed.startsWith("`") && - trimmed.endsWith("`") - ) { - return trimmed.slice(1, -1) === GROUP_NO_REPLY_MARKER; + let candidate = text.trim(); + if (!candidate) return false; + // Unwrap a single fenced code block (e.g. ```\n[[NO_REPLY]]\n``` or ```text\n[[NO_REPLY]]\n```). + const fenced = /^(`{3,}|~{3,})[^\n]*\r?\n([\s\S]*?)\r?\n\1$/u.exec(candidate); + if (fenced) { + candidate = (fenced[2] ?? "").trim(); + } + // Unwrap matching lightweight formatting wrappers (backticks, quotes, bold/italic). + for (let pass = 0; pass < 3; pass++) { + const prev = candidate; + if (candidate.startsWith("**") && candidate.endsWith("**") && candidate.length > 4) { + candidate = candidate.slice(2, -2).trim(); + } else if (candidate.startsWith("__") && candidate.endsWith("__") && candidate.length > 4) { + candidate = candidate.slice(2, -2).trim(); + } else if ( + candidate.length > 2 && + ((candidate.startsWith("`") && candidate.endsWith("`")) || + (candidate.startsWith('"') && candidate.endsWith('"')) || + (candidate.startsWith("'") && candidate.endsWith("'")) || + (candidate.startsWith("*") && candidate.endsWith("*")) || + (candidate.startsWith("_") && candidate.endsWith("_"))) + ) { + candidate = candidate.slice(1, -1).trim(); + } + if (candidate === prev) break; } - return false; + candidate = candidate.replace(/[.。!!]+$/u, "").trim(); + return candidate === GROUP_NO_REPLY_MARKER; +} + +const GROUP_NO_REPLY_DIRECTIVE_PATTERN = + /(?:^|[\s([{"'`*_:;,\-—(【「『“‘:;,、])\[\[NO_REPLY\]\](?:$|[\s)\]}"'`*_.,!?;:。!?;:,、)】」』”’])/u; + +/** + * True when Agent prose (outside Markdown code) includes the standalone `[[NO_REPLY]]` marker, + * signaling that the reply must not trigger downstream agent relays even if short prose accompanied it. + */ +export function hasGroupNoReplyDirective(text: string): boolean { + if (isGroupNoReply(text)) return true; + const prose = maskGroupMentionCode(text); + return GROUP_NO_REPLY_DIRECTIVE_PATTERN.test(prose); } export const remoteGroupRoomIdSchema = z.string().regex(/^remote:[A-Za-z0-9_-]{8,512}$/u); @@ -233,6 +265,7 @@ export const GROUPS_LIST_METHOD = "codexhost/groups/list"; export const GROUPS_GET_METHOD = "codexhost/groups/get"; export const GROUPS_CREATE_METHOD = "codexhost/groups/create"; export const GROUPS_UPDATE_METHOD = "codexhost/groups/update"; +export const GROUPS_STOP_METHOD = "codexhost/groups/stop"; export const GROUPS_DELETE_METHOD = "codexhost/groups/delete"; export const GROUPS_ADD_MEMBER_METHOD = "codexhost/groups/member/add"; export const GROUPS_UPDATE_MEMBER_METHOD = "codexhost/groups/member/update"; @@ -311,6 +344,11 @@ export const groupsUpdateParamsSchema = z } }); export const groupsUpdateResultSchema = groupsCreateResultSchema; +export const groupsStopParamsSchema = z.strictObject(roomIdentity); +export const groupsStopResultSchema = z.object({ + room: groupRoomSchema, + clearedPendingMemberIds: z.array(groupMemberIdSchema), +}); export const groupsDeleteParamsSchema = z.strictObject(roomIdentity); export const groupsDeleteResultSchema = z.object({ deleted: z.boolean() }); export const groupsAddMemberParamsSchema = z.strictObject({ @@ -536,6 +574,8 @@ export type GroupsCreateParams = z.infer; export type GroupsCreateResult = z.infer; export type GroupsUpdateParams = z.infer; export type GroupsUpdateResult = z.infer; +export type GroupsStopParams = z.infer; +export type GroupsStopResult = z.infer; export type GroupsDeleteParams = z.infer; export type GroupsDeleteResult = z.infer; export type GroupsAddMemberParams = z.infer; diff --git a/packages/shared-contracts/test/group-chat.test.ts b/packages/shared-contracts/test/group-chat.test.ts index 813acda77c..11997fb962 100644 --- a/packages/shared-contracts/test/group-chat.test.ts +++ b/packages/shared-contracts/test/group-chat.test.ts @@ -208,6 +208,14 @@ describe("Group Chat contracts", () => { contracts.groupsUpdateResultSchema, { room }, ], + [ + "stop", + contracts.GROUPS_STOP_METHOD, + contracts.groupsStopParamsSchema, + { roomId }, + contracts.groupsStopResultSchema, + { room: { ...room, relayPaused: true }, clearedPendingMemberIds: [memberId] }, + ], [ "delete", contracts.GROUPS_DELETE_METHOD, @@ -561,8 +569,48 @@ describe("Group Chat contracts", () => { expect(contracts.isGroupNoReply(contracts.GROUP_NO_REPLY_MARKER)).toBe(true); expect(contracts.isGroupNoReply(` ${contracts.GROUP_NO_REPLY_MARKER}\n`)).toBe(true); expect(contracts.isGroupNoReply(`\`${contracts.GROUP_NO_REPLY_MARKER}\``)).toBe(true); + expect(contracts.isGroupNoReply(`\`\`\`\n${contracts.GROUP_NO_REPLY_MARKER}\n\`\`\``)).toBe( + true, + ); + expect( + contracts.isGroupNoReply(`\`\`\`text\n ${contracts.GROUP_NO_REPLY_MARKER} \n\`\`\``), + ).toBe(true); + expect(contracts.isGroupNoReply(`**${contracts.GROUP_NO_REPLY_MARKER}**`)).toBe(true); + expect(contracts.isGroupNoReply(`"${contracts.GROUP_NO_REPLY_MARKER}"`)).toBe(true); + expect(contracts.isGroupNoReply(`${contracts.GROUP_NO_REPLY_MARKER}.`)).toBe(true); + expect(contracts.isGroupNoReply(`${contracts.GROUP_NO_REPLY_MARKER}。`)).toBe(true); expect(contracts.isGroupNoReply(`${contracts.GROUP_NO_REPLY_MARKER} extra`)).toBe(false); expect(contracts.isGroupNoReply("Done")).toBe(false); + + expect(contracts.hasGroupNoReplyDirective(contracts.GROUP_NO_REPLY_MARKER)).toBe(true); + expect( + contracts.hasGroupNoReplyDirective( + `Waiting on @architect before taking action.\n${contracts.GROUP_NO_REPLY_MARKER}`, + ), + ).toBe(true); + expect( + contracts.hasGroupNoReplyDirective(`No action needed (${contracts.GROUP_NO_REPLY_MARKER}).`), + ).toBe(true); + expect(contracts.hasGroupNoReplyDirective(`状态:${contracts.GROUP_NO_REPLY_MARKER}`)).toBe( + true, + ); + expect(contracts.hasGroupNoReplyDirective(`status:${contracts.GROUP_NO_REPLY_MARKER}`)).toBe( + true, + ); + expect(contracts.hasGroupNoReplyDirective(`(${contracts.GROUP_NO_REPLY_MARKER})`)).toBe(true); + expect( + contracts.hasGroupNoReplyDirective(`Use \`${contracts.GROUP_NO_REPLY_MARKER}\` when silent.`), + ).toBe(false); + expect(contracts.hasGroupNoReplyDirective(`\`状态:${contracts.GROUP_NO_REPLY_MARKER}\``)).toBe( + false, + ); + expect(contracts.hasGroupNoReplyDirective(`foo${contracts.GROUP_NO_REPLY_MARKER}`)).toBe(false); + expect( + contracts.hasGroupNoReplyDirective( + `\`\`\`\n${contracts.GROUP_NO_REPLY_MARKER} example\n\`\`\`\nPlease @reviewer check this.`, + ), + ).toBe(false); + expect(contracts.hasGroupNoReplyDirective("Done")).toBe(false); }); it("validates a groups-changed cursor with or without a room ID", () => { diff --git a/packages/web-server/src/ch-host-client.ts b/packages/web-server/src/ch-host-client.ts index 5d208d9244..18846715ac 100644 --- a/packages/web-server/src/ch-host-client.ts +++ b/packages/web-server/src/ch-host-client.ts @@ -28,6 +28,7 @@ import { GROUPS_READ_MESSAGES_METHOD, GROUPS_REBIND_MEMBER_METHOD, GROUPS_REMOVE_MEMBER_METHOD, + GROUPS_STOP_METHOD, GROUPS_UPDATE_MEMBER_METHOD, GROUPS_UPDATE_MEMORY_METHOD, GROUPS_UPDATE_METHOD, @@ -152,6 +153,7 @@ const METHODS = new Set([ GROUPS_GET_METHOD, GROUPS_CREATE_METHOD, GROUPS_UPDATE_METHOD, + GROUPS_STOP_METHOD, GROUPS_DELETE_METHOD, GROUPS_ADD_MEMBER_METHOD, GROUPS_UPDATE_MEMBER_METHOD, diff --git a/packages/web-server/src/groups.ts b/packages/web-server/src/groups.ts index ff4d1fc218..a3a486bd29 100644 --- a/packages/web-server/src/groups.ts +++ b/packages/web-server/src/groups.ts @@ -11,6 +11,7 @@ import { GROUPS_READ_MESSAGES_METHOD, GROUPS_REBIND_MEMBER_METHOD, GROUPS_REMOVE_MEMBER_METHOD, + GROUPS_STOP_METHOD, GROUPS_UPDATE_MEMBER_METHOD, GROUPS_UPDATE_MEMORY_METHOD, GROUPS_UPDATE_METHOD, @@ -36,6 +37,8 @@ import { groupsRebindMemberResultSchema, groupsRemoveMemberParamsSchema, groupsRemoveMemberResultSchema, + groupsStopParamsSchema, + groupsStopResultSchema, groupsUpdateMemberParamsSchema, groupsUpdateMemberResultSchema, groupsUpdateMemoryParamsSchema, @@ -152,6 +155,36 @@ function roomUpdatedAtMs(room: GroupRoom): number { return Number.isFinite(parsed) ? parsed : 0; } +function isUnsupportedGroupMethodError(error: unknown): boolean { + if (typeof error === "object" && error !== null) { + const record = error as { code?: unknown; details?: unknown }; + const code = record.code; + if ( + code === -32601 || + code === "rpc/method-not-found" || + code === "gateway/not-found" || + code === "host/method-unavailable" + ) { + return true; + } + if (typeof record.details === "object" && record.details !== null) { + const details = record.details as { hostCode?: unknown; code?: unknown }; + if ( + details.hostCode === -32601 || + details.hostCode === "gateway/not-found" || + details.code === "gateway/not-found" || + details.code === "rpc/method-not-found" + ) { + return true; + } + } + } + const message = error instanceof Error ? error.message : String(error); + return /unknown group room method|method is not available|method not found|no handler for/iu.test( + message, + ); +} + export interface WebGroupsOptions { readonly remoteListTimeoutMs?: number; } @@ -312,6 +345,36 @@ export class WebGroups { return projected; }); + rpc.register(GROUPS_STOP_METHOD, async (args) => { + const parsed = parseOrThrow(groupsStopParamsSchema, args); + const { peer, nativeRoomId } = this.resolveTarget(parsed.roomId); + const targetHost = peer?.host ?? this.host; + let result: z.infer; + try { + const raw = await targetHost.request(GROUPS_STOP_METHOD, { roomId: nativeRoomId }); + result = groupsStopResultSchema.parse(raw); + } catch (error) { + if (!isUnsupportedGroupMethodError(error)) throw error; + // Legacy hosts without `codexhost/groups/stop` fall back to pausing automatic relays. + const fallback = groupsUpdateResultSchema.parse( + await targetHost.request(GROUPS_UPDATE_METHOD, { + roomId: nativeRoomId, + relayPaused: true, + }), + ); + result = { room: fallback.room, clearedPendingMemberIds: [] }; + } + const projected = + peer === undefined + ? result + : { + room: projectRemoteRoom(peer, result.room), + clearedPendingMemberIds: result.clearedPendingMemberIds, + }; + this.emitChanged(projected.room.roomId); + return projected; + }); + rpc.register(GROUPS_DELETE_METHOD, async (args) => { const parsed = parseOrThrow(groupsDeleteParamsSchema, args); const { peer, nativeRoomId } = this.resolveTarget(parsed.roomId); diff --git a/packages/web-server/test/ch-groups.test.ts b/packages/web-server/test/ch-groups.test.ts index 023f8854aa..53b919a84a 100644 --- a/packages/web-server/test/ch-groups.test.ts +++ b/packages/web-server/test/ch-groups.test.ts @@ -17,6 +17,7 @@ import { GROUPS_READ_MESSAGES_METHOD, GROUPS_REBIND_MEMBER_METHOD, GROUPS_REMOVE_MEMBER_METHOD, + GROUPS_STOP_METHOD, GROUPS_UPDATE_MEMBER_METHOD, GROUPS_UPDATE_MEMORY_METHOD, GROUPS_UPDATE_METHOD, @@ -31,7 +32,7 @@ import { REMOTE_GROUPS_LIST_TIMEOUT_MS, WebGroups, remoteGroupRoomId } from "../ import { PeerChHostClient } from "../src/peer-ch-host-client.ts"; import { PeerHostClient } from "../src/peer-host-client.ts"; import { remoteSessionId } from "../src/remote-sessions.ts"; -import { EventHub, RpcRegistry, type StreamSink } from "../src/transport.ts"; +import { EventHub, RpcError, RpcRegistry, type StreamSink } from "../src/transport.ts"; import { FakeChHost, startFakeChDebugger } from "./support/ch-host.ts"; const ROOM_ID = "11111111-1111-4111-8111-111111111111"; @@ -90,6 +91,7 @@ const ALL_GROUP_METHODS = [ GROUPS_GET_METHOD, GROUPS_CREATE_METHOD, GROUPS_UPDATE_METHOD, + GROUPS_STOP_METHOD, GROUPS_DELETE_METHOD, GROUPS_ADD_MEMBER_METHOD, GROUPS_UPDATE_MEMBER_METHOD, @@ -119,6 +121,10 @@ it("proxies all Group Chat RPCs, validates schemas, and emits change events on w memoryMaxBytes: 16_384, }, }, + [GROUPS_STOP_METHOD]: { + room: { ...ROOM, relayPaused: true }, + clearedPendingMemberIds: [MEMBER_ID], + }, [GROUPS_DELETE_METHOD]: { deleted: true }, [GROUPS_ADD_MEMBER_METHOD]: { room: ROOM, member: MEMBER }, [GROUPS_UPDATE_MEMBER_METHOD]: { room: ROOM, member: { ...MEMBER, status: "muted" } }, @@ -194,6 +200,7 @@ it("proxies all Group Chat RPCs, validates schemas, and emits change events on w }, writes: true, }, + { method: GROUPS_STOP_METHOD, args: { roomId: ROOM_ID }, writes: true }, { method: GROUPS_DELETE_METHOD, args: { roomId: ROOM_ID }, writes: true }, { method: GROUPS_ADD_MEMBER_METHOD, @@ -283,6 +290,7 @@ it("rejects invalid Group Chat RPC params with groups/invalid before calling Hos { method: GROUPS_GET_METHOD, args: { roomId: "not-a-uuid" } }, { method: GROUPS_CREATE_METHOD, args: { defaultCwd: " ", members: [] } }, { method: GROUPS_UPDATE_METHOD, args: { roomId: ROOM_ID, maxAgentHops: 201 } }, + { method: GROUPS_STOP_METHOD, args: { roomId: "not-a-uuid" } }, { method: GROUPS_UPDATE_METHOD, args: { roomId: ROOM_ID, memoryMaxBytes: GROUP_MEMORY_MIN_BYTES - 1 }, @@ -1092,6 +1100,149 @@ it("times out a hanging remote peer within the server list budget and returns he groups.close(); }); +it("falls back to pausing relays when a legacy remote peer does not implement codexhost/groups/stop", async () => { + const HOST_ID = "peer-legacy-stop"; + const REMOTE_ROOM_ID = "99999999-9999-4999-8999-999999999999"; + const PROJECTED_ID = remoteGroupRoomId(HOST_ID, REMOTE_ROOM_ID); + const calls: Array<{ method: string; params: Record }> = []; + const emitted: Array<{ event: string; args: unknown[] }> = []; + + const legacyPeer = { + hostId: HOST_ID, + displayName: "legacy", + state: "connected", + online: true, + host: { + request: async (method: string, params: Record) => { + calls.push({ method, params }); + if (method === GROUPS_STOP_METHOD) { + throw Object.assign(new Error("Unknown Group Room method"), { code: -32601 }); + } + if (method === GROUPS_UPDATE_METHOD) { + return { room: { ...ROOM, roomId: REMOTE_ROOM_ID, relayPaused: true } } as T; + } + throw new Error(`unexpected method ${method}`); + }, + }, + }; + + const rpc = new RpcRegistry(); + const groups = new WebGroups( + { + request: async () => { + throw new Error("unexpected local call"); + }, + }, + { emit: (event: string, ...args: unknown[]) => void emitted.push({ event, args }) }, + { + peers: () => [legacyPeer], + peer: (hostId) => (hostId === HOST_ID ? legacyPeer : undefined), + }, + ); + groups.register(rpc); + + const res = await rpc.dispatch(GROUPS_STOP_METHOD, { args: { roomId: PROJECTED_ID } }); + assert.equal(res.ok, true, res.ok ? undefined : res.error.message); + if (res.ok) { + assert.deepEqual(res.value, { + room: { + ...ROOM, + roomId: PROJECTED_ID, + relayPaused: true, + members: [{ ...MEMBER, threadId: remoteSessionId(HOST_ID, MEMBER.threadId) }], + remote: { hostId: HOST_ID, displayName: "legacy", state: "connected" }, + }, + clearedPendingMemberIds: [], + }); + } + assert.deepEqual(calls, [ + { method: GROUPS_STOP_METHOD, params: { roomId: REMOTE_ROOM_ID } }, + { method: GROUPS_UPDATE_METHOD, params: { roomId: REMOTE_ROOM_ID, relayPaused: true } }, + ]); + assert.deepEqual(emitted, [{ event: GROUPS_CHANGED_EVENT, args: [{ roomId: PROJECTED_ID }] }]); + groups.close(); +}); + +it("falls back on remote/request-failed gateway/not-found and hostCode -32601 stop errors, but propagates real failures", async () => { + const HOST_ID = "peer-v35-stop"; + const REMOTE_ROOM_ID = "99999999-9999-4999-8999-999999999998"; + const PROJECTED_ID = remoteGroupRoomId(HOST_ID, REMOTE_ROOM_ID); + + const unsupportedErrors: unknown[] = [ + new RpcError("remote/request-failed", "codexhost: no handler for codexhost/groups/stop", { + code: "gateway/not-found", + }), + new RpcError("remote/request-failed", "Unknown remote RPC", { hostCode: -32601 }), + new RpcError("host/method-unavailable", "Host does not support stop"), + ]; + + for (const stopError of unsupportedErrors) { + const calls: string[] = []; + const peer = { + hostId: HOST_ID, + displayName: "v35", + state: "connected", + online: true, + host: { + request: async (method: string) => { + calls.push(method); + if (method === GROUPS_STOP_METHOD) throw stopError; + if (method === GROUPS_UPDATE_METHOD) { + return { room: { ...ROOM, roomId: REMOTE_ROOM_ID, relayPaused: true } } as T; + } + throw new Error(`unexpected method ${method}`); + }, + }, + }; + const rpc = new RpcRegistry(); + const groups = new WebGroups( + { + request: async () => { + throw new Error("unexpected local call"); + }, + }, + { emit: () => {} }, + { peers: () => [peer], peer: (id) => (id === HOST_ID ? peer : undefined) }, + ); + groups.register(rpc); + const res = await rpc.dispatch(GROUPS_STOP_METHOD, { args: { roomId: PROJECTED_ID } }); + assert.equal(res.ok, true, res.ok ? undefined : res.error.message); + assert.deepEqual(calls, [GROUPS_STOP_METHOD, GROUPS_UPDATE_METHOD]); + groups.close(); + } + + // Real operational failures must never silently downgrade into groups/update. + const failingCalls: string[] = []; + const failingPeer = { + hostId: HOST_ID, + displayName: "failing", + state: "connected", + online: true, + host: { + request: async () => { + failingCalls.push("called"); + throw new RpcError("remote/timeout", "Remote stop timed out."); + }, + }, + }; + const failingRpc = new RpcRegistry(); + const failingGroups = new WebGroups( + { + request: async () => { + throw new Error("unexpected local call"); + }, + }, + { emit: () => {} }, + { peers: () => [failingPeer], peer: (id) => (id === HOST_ID ? failingPeer : undefined) }, + ); + failingGroups.register(failingRpc); + const failed = await failingRpc.dispatch(GROUPS_STOP_METHOD, { args: { roomId: PROJECTED_ID } }); + assert.equal(failed.ok, false); + if (!failed.ok) assert.equal(failed.error.code, "remote/timeout"); + assert.equal(failingCalls.length, 1); + failingGroups.close(); +}); + it("blocks leaderMemberId updates to legacy remote peers without leaderMode capability and forwards when supported", async () => { const LEGACY_HOST_ID = "peer-legacy-leader"; const MODERN_HOST_ID = "peer-modern-leader";