Skip to content

Commit ec91c4d

Browse files
authored
feat(chat): support independent multi-recipient handoffs (#7787)
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent b0768d9 commit ec91c4d

32 files changed

Lines changed: 729 additions & 143 deletions

‎apps/presentation/dashboard/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
"smoke:goal-acceptance-contract-packaged": "LOOPX_ACCEPTANCE_CONTRACT_PACKAGED=1 LOOPX_ACCEPTANCE_CONTRACT_PORT=5297 LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/goal-acceptance-contract-browser-smoke.mjs",
5656
"smoke:status-projection-contract": "rm -rf /tmp/loopx-status-projection-contract-smoke && tsc --ignoreConfig --target ES2022 --module CommonJS --moduleResolution Node --ignoreDeprecations 6.0 --skipLibCheck --strict --resolveJsonModule --esModuleInterop --outDir /tmp/loopx-status-projection-contract-smoke smoke/status-projection-contract-smoke.ts src/data/status.ts src/data/status-merge.ts src/data/status-request-fence.ts && NODE_PATH=\"$PWD/node_modules\" node /tmp/loopx-status-projection-contract-smoke/apps/presentation/dashboard/smoke/status-projection-contract-smoke.js",
5757
"smoke:team-plan-recovery": "vite build --ssr smoke/team-plan-recovery-smoke.mjs --outDir node_modules/.cache/loopx-team-plan-recovery --emptyOutDir && node node_modules/.cache/loopx-team-plan-recovery/team-plan-recovery-smoke.js",
58+
"smoke:multi-recipient": "node smoke/multi-recipient-browser-smoke.mjs",
5859
"smoke:team-plan-proposal": "tsc --ignoreConfig --target ES2022 --module ES2022 --moduleResolution Bundler --ignoreDeprecations 6.0 --jsx react-jsx --types node --skipLibCheck --strict --rootDir ../../.. --outDir node_modules/.cache/loopx-team-plan-smoke smoke/team-plan-proposal-smoke.ts src/data/chat.ts src/features/personal-workspace/team-plan-preview.ts src/vite-env.d.ts && node node_modules/.cache/loopx-team-plan-smoke/apps/presentation/dashboard/smoke/team-plan-proposal-smoke.js",
5960
"smoke:status-source-switch-browser": "node ../../../examples/status-source-switch-browser-smoke.mjs",
6061
"smoke:status-source-switch-packaged": "LOOPX_STATUS_SOURCE_SWITCH_PACKAGED=1 LOOPX_STATUS_SOURCE_SWITCH_PORT=5198 node ../../../examples/status-source-switch-browser-smoke.mjs",
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// One request, independent recipient states and returns over the packaged real backend.
2+
import assert from 'node:assert/strict';
3+
import {spawn} from 'node:child_process';
4+
import {once} from 'node:events';
5+
import {mkdir} from 'node:fs/promises';
6+
import {resolve} from 'node:path';
7+
import {createInterface} from 'node:readline';
8+
import {testPythonCommand} from '../../../../scripts/test-python.mjs';
9+
import {launchBrowser, loadPlaywright} from '../../../../examples/dashboard-browser-smoke-support.mjs';
10+
const repo = resolve(import.meta.dirname, '../../../..');
11+
const output = resolve(repo, 'output/playwright/multi-recipient');
12+
await mkdir(output, {recursive:true});
13+
const fixturePath = resolve(repo, 'examples/personal-workspace-browser/steward_requests_fixture.py');
14+
const command = testPythonCommand(`import runpy; runpy.run_path(${JSON.stringify(fixturePath)}, run_name="__main__")`, {repoRoot:repo});
15+
const child = spawn(command.command, [...command.args, '--status-file', resolve(repo, 'examples/status.example.json'),
16+
'--multi-recipient'], {cwd:repo, env:{...process.env, LOOPX_USAGE_PING:'0'}, stdio:['pipe','pipe','pipe']});
17+
const exited = once(child, 'exit');
18+
let stderr = '';
19+
child.stderr.on('data', value => stderr += value);
20+
const queue = [], waiting = [];
21+
createInterface({input:child.stdout}).on('line', line => {
22+
try {const value=JSON.parse(line); if(waiting.length) waiting.shift()(value); else queue.push(value);} catch { /* CLI banner */ }
23+
});
24+
const next = () => new Promise((resolve, reject) => {
25+
const timer=setTimeout(()=>reject(Error(`Fixture timeout: ${stderr}`)),90000);
26+
const receive=value=>{clearTimeout(timer);resolve(value);};
27+
if(queue.length) receive(queue.shift()); else waiting.push(receive);
28+
});
29+
async function fixture(action) {child.stdin.write(action+'\n');return next();}
30+
let browser;
31+
try {
32+
const ready=await next();assert.equal(ready.event,'ready');
33+
browser=await launchBrowser(loadPlaywright().chromium);
34+
const page=await browser.newPage({viewport:{width:1200,height:888}});
35+
await page.addInitScript(()=>localStorage.setItem('loopx-pw-locale','zh-CN'));
36+
await page.goto(ready.origin+'/chat/');
37+
await page.getByRole('navigation',{name:'管家视图'}).getByRole('button',{name:/^(Chat|对话)$/}).click();
38+
const cards=page.locator('.personal-collaboration').filter({hasText:'核对迁移方案 ·'});
39+
await cards.first().waitFor(); assert.equal(await cards.count(),2);
40+
const builder=cards.filter({hasText:'核对迁移方案 · builder'});
41+
const reviewer=cards.filter({hasText:'核对迁移方案 · reviewer'});
42+
assert.match(await builder.innerText(),/尚未记录/);
43+
assert.match(await reviewer.innerText(),/已采纳/);
44+
await page.screenshot({path:resolve(output,'conversation.png')});
45+
const summary=builder.locator('summary');
46+
await summary.focus();await page.keyboard.press('Enter');
47+
await builder.getByText('背景与补充',{exact:true}).waitFor();
48+
await page.setViewportSize({width:390,height:844});
49+
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
50+
await page.screenshot({path:resolve(output,'recipient-detail.png')});
51+
await summary.press('Enter');
52+
const before=await fixture('inspect');
53+
await fixture('report-multi');
54+
// The real pending-return observer must discover the reply without a reload.
55+
await page.waitForFunction(()=>[...document.querySelectorAll('.personal-collaboration')].some(
56+
row=>row.textContent.includes('核对迁移方案 · reviewer')&&row.textContent.includes('回复已送达')),null,{timeout:45000});
57+
assert.doesNotMatch(await builder.innerText(),/回复已送达/);
58+
await page.getByText('reviewer 已完成独立核查;builder 的结论仍待返回。',{exact:true}).waitFor();
59+
const after=await fixture('inspect');
60+
assert.equal(after.turn_count,before.turn_count);
61+
assert.equal(after.posts,before.posts,'Observation and result refresh create no additional writes');
62+
console.log(JSON.stringify({ok:true,recipient_count:2,automatic_return:true,remaining_recipient:'builder',
63+
additional_browser_writes:after.posts-before.posts,output}));
64+
} finally {
65+
await browser?.close();
66+
if(child.exitCode===null){child.stdin.write('stop\n');await exited;}
67+
}

‎apps/presentation/dashboard/src/data/chat.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -899,6 +899,7 @@ export type ChatVisibleMessage = {
899899
/** Client-side lineage added when messages from several Sessions are merged. */
900900
session_id?: string;
901901
collaboration?: CollaborationReadback;
902+
collaborations?: CollaborationReadback[];
902903
origin?: string;
903904
attachments?: ChatImageAttachment[];
904905
/** Read-only original-source view; text remains the canonical model input. */

‎apps/presentation/dashboard/src/data/conversation-returns.test.mjs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,32 @@ assert.equal(queueReadback.length, 1, "Queue admission/history races retain exac
112112
assert.equal(queueReadback[0].sourceMessageId, "user-message");
113113
const crossSession = [...queueReadback, {...queueReadback[0], sourceSessionId: "different"}];
114114
assert.equal(reconcileConversationHistory(crossSession, [storedRoles[0]], createHistory).length, 2, "Message ids are scoped to their original Session");
115+
116+
// One recipient's delivered result must not hide another outstanding answer.
117+
const multiple = [{sourceSessionId: "original", text: "Ask both", collaborations: [
118+
{request_id: "a", returns: [{phase: "conclusion", status: "delivered"}]},
119+
{request_id: "b", returns: []},
120+
]}];
121+
assert.deepEqual(conversationPendingReturnSessions(multiple), ["original"]);
122+
const both = multiple[0].collaborations.map(row => ({...row, returns: [{phase: "conclusion", status: "delivered"}]}));
123+
const identified = [{...multiple[0], sourceMessageId: "multi"}];
124+
const observedBoth = reconcileConversationReturns(identified, "original", [
125+
{message_id: "multi", collaborations: both},
126+
], createReply);
127+
assert.equal(observedBoth[0].text, "Ask both");
128+
assert.deepEqual(conversationPendingReturnSessions(observedBoth), []);
129+
assert.equal(reconcileConversationReturns(observedBoth, "original", [{message_id: "multi"}], createReply), observedBoth);
130+
131+
// A revised brief keeps its return obligation despite a delivered old conclusion.
132+
const revised = [{sourceSessionId: "original", collaborations: [
133+
{request_id: "a", request_revision: 2, returns: [{phase: "conclusion", status: "delivered", request_revision: 1}]},
134+
{request_id: "b", returns: [{phase: "conclusion", status: "delivered"}]},
135+
]}];
136+
assert.deepEqual(conversationPendingReturnSessions(revised), ["original"]);
137+
revised[0].collaborations[0].returns.push({phase: "conclusion", status: "queued", request_revision: 2});
138+
assert.deepEqual(conversationPendingReturnSessions(revised), ["original"]);
139+
revised[0].collaborations[0].returns[1].status = "delivered";
140+
assert.deepEqual(conversationPendingReturnSessions(revised), []);
141+
142+
revised[0].collaborations[0].returns.unshift({phase: "conclusion", status: "superseded", request_revision: 2});
143+
assert.deepEqual(conversationPendingReturnSessions(revised), [], "A superseded result cannot hide the delivered current conclusion");

‎apps/presentation/dashboard/src/data/conversation-returns.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ type ConversationMessage = {
88
role?: string;
99
pending?: boolean;
1010
collaboration?: ChatVisibleMessage["collaboration"];
11+
collaborations?: ChatVisibleMessage["collaborations"];
1112
returnDelivery?: ChatVisibleMessage["return_delivery"];
1213
replyContext?: ChatVisibleMessage["reply_context"];
1314
text?: string;
@@ -20,13 +21,20 @@ export function conversationReturnSessions(activeSessionId: string | undefined,
2021
return [...sessions].sort();
2122
}
2223

24+
/** Only the current brief's conclusion can settle its outstanding return. */
25+
export function currentCollaborationConclusion(request: NonNullable<ChatVisibleMessage["collaboration"]>) {
26+
const replies = request.returns.filter(reply => reply.phase === "conclusion"
27+
&& (request.request_revision === undefined || (reply.request_revision ?? 1) === request.request_revision));
28+
return replies.find(reply => reply.status === "delivered")
29+
?? replies.find(reply => reply.status !== "superseded") ?? replies[0];
30+
}
31+
2332
/** Metadata can change before a new transcript row is appended. */
2433
export function conversationPendingReturnSessions(messages: ConversationMessage[]): string[] {
2534
const sessions = new Set<string>();
2635
for (const message of messages) {
27-
const waitingForConclusion = message.collaboration && !message.collaboration.returns.some(
28-
(reply) => reply.phase === "conclusion" && reply.status === "delivered",
29-
);
36+
const requests = message.collaborations ?? (message.collaboration ? [message.collaboration] : []);
37+
const waitingForConclusion = requests.some(request => currentCollaborationConclusion(request)?.status !== "delivered");
3038
const delivery = message.returnDelivery;
3139
const waitingForDelivery = delivery && !["delivered", "superseded"].includes(delivery.status);
3240
const waitingForTranscript = message.sourceTurnId && !message.sourceMessageId;
@@ -61,17 +69,19 @@ export function reconcileConversationReturns<T extends ConversationMessage>(
6169
// its outstanding read obligation until a newer observation arrives.
6270
const returnDelivery = source.return_delivery ?? row.returnDelivery;
6371
const collaboration = source.collaboration ?? row.collaboration;
72+
const collaborations = source.collaborations ?? row.collaborations;
6473
const sourceCreatedAt = source.created_at ?? row.sourceCreatedAt;
6574
const replyContext = source.reply_context ?? row.replyContext;
6675
// Only the exact canonical user body can switch to its source-backed view.
6776
// A background read never replaces a live answer or a different draft.
6877
const text = row.role === "user" && source.reply_context && row.text === source.text
6978
? source.reply_context.source_text : row.text;
7079
if (row.sourceMessageId === source.message_id && JSON.stringify(row.returnDelivery) === JSON.stringify(returnDelivery)
71-
&& JSON.stringify(row.collaboration) === JSON.stringify(collaboration) && row.sourceCreatedAt === sourceCreatedAt
80+
&& JSON.stringify(row.collaboration) === JSON.stringify(collaboration)
81+
&& JSON.stringify(row.collaborations) === JSON.stringify(collaborations) && row.sourceCreatedAt === sourceCreatedAt
7282
&& JSON.stringify(row.replyContext) === JSON.stringify(replyContext) && row.text === text) return row;
7383
changed = true;
74-
return { ...row, sourceMessageId: source.message_id, sourceCreatedAt, returnDelivery, collaboration, replyContext, text };
84+
return { ...row, sourceMessageId: source.message_id, sourceCreatedAt, returnDelivery, collaboration, collaborations, replyContext, text };
7585
});
7686
for (const message of messages) {
7787
if (message.origin !== "manager_followup" || seen.has(message.message_id)) continue;

‎apps/presentation/dashboard/src/features/personal-workspace/channel-timeline.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { MessageActivity } from "./message-activity";
33
import { GoalDraftCard } from "./goal-draft-card";
44
import type { GoalDraft } from "../../../../../../loopx/control_plane/collaboration/goal_draft.js";
55
import {Fragment, useLayoutEffect, useRef, useState} from "react";
6-
import { CollaborationCard } from "./collaboration-card";
6+
import { CollaborationCards } from "./collaboration-card";
77
import {ConversationReplyContext} from "./conversation-requests";
88
import { Activity, Bot, Sparkles } from "lucide-react";
99

@@ -210,7 +210,7 @@ export function ChannelTimeline({
210210
{item.message.role !== "user" && (item.message.pending || item.message.sourceTurnId || item.message.activity?.length || item.message.steps?.length) ? <MessageActivity message={item.message} onCancelPreparation={onCancelPreparation} onInterruptTurn={onInterruptTurn} onAdjustTurn={onAdjustTurn}/> : null}
211211
{item.message.role === "assistant" && !item.message.pending && item.message.goalDraft
212212
? <GoalDraftCard draftId={`${item.message.sourceSessionId ?? ""}:${item.message.id}`} draft={item.message.goalDraft} onReview={onReviewGoalDraft} onSuggest={onSuggestReply}/> : null}
213-
<CollaborationCard request={item.message.collaboration} />
213+
<CollaborationCards request={item.message.collaboration} requests={item.message.collaborations} />
214214
<ReturnDeliveryStatus delivery={item.message.returnDelivery} />
215215
</div>
216216
</article>

‎apps/presentation/dashboard/src/features/personal-workspace/collaboration-card.tsx‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { CollaborationReadback } from "../../data/chat-model";
2+
import {currentCollaborationConclusion} from "../../data/conversation-returns";
23
import {useEffect, useState} from "react";
34
import type {RequestControlView} from "../../data/request-control";
45
import {RequestControl} from "./request-control";
@@ -54,8 +55,7 @@ export function CollaborationCard({ request }: { request?: CollaborationReadback
5455
default: return c.unknown;
5556
}
5657
})();
57-
const conclusion = request.returns.find((reply) => reply.phase === "conclusion" &&
58-
(revision === undefined || (reply.request_revision === undefined ? 1 : reply.request_revision) === revision));
58+
const conclusion = currentCollaborationConclusion({...request, request_revision: revision});
5959
const decisionReason = observed ? observed.assessment?.reason : request.decision_reason;
6060
return <section className="personal-collaboration" aria-label={c.title}>
6161
<header><strong>{brief.purpose}</strong><span>{c.owner}: {request.goal_id ? `${request.goal_id} / ` : ""}{request.agent_id}</span></header>
@@ -81,3 +81,9 @@ export function CollaborationCard({ request }: { request?: CollaborationReadback
8181
</details>
8282
</section>;
8383
}
84+
85+
/** Each recipient retains its own request controls, decision and return. */
86+
export function CollaborationCards({request, requests}: {request?: CollaborationReadback; requests?: CollaborationReadback[]}) {
87+
return <>{(requests ?? (request ? [request] : [])).map(row =>
88+
<CollaborationCard key={row.request_id} request={row} />)}</>;
89+
}

‎apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,7 @@ export type WorkspaceMessage = {
399399
activity?: string[];
400400
steps?: TurnStep[];
401401
collaboration?: CollaborationReadback;
402+
collaborations?: CollaborationReadback[];
402403
agentLabel?: string;
403404
attachments?: WorkspaceImageAttachment[];
404405
id: string;

‎apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { composerKeyAction } from "./composer-keyboard";
1313
import type { ConversationHistoryStatus } from "../../data/use-conversation-history";
1414
import { GoalDraftCard } from "./goal-draft-card";
1515
import type { GoalDraft } from "../../../../../../loopx/control_plane/collaboration/goal_draft.js";
16-
import { CollaborationCard } from "./collaboration-card";
16+
import { CollaborationCards } from "./collaboration-card";
1717
import {ConversationRequests, ConversationReplyContext, OriginalProjectRequests} from "./conversation-requests";
1818
import {
1919
compileActionReviewPlan,
@@ -484,7 +484,7 @@ function ManagerConversationTray({
484484
<ConversationReplyContext context={message.replyContext} zh={locale === "zh-CN"}/>
485485
{message.role === "assistant" ? <MessageActivity message={message} onInterruptTurn={onInterruptTurn} onAdjustTurn={onAdjustTurn} onCancelPreparation={onCancelPreparation} /> : null}
486486
{message.role === "assistant" && !message.pending && message.goalDraft ? <GoalDraftCard draftId={`${message.sourceSessionId ?? ""}:${message.id}`} draft={message.goalDraft} onReview={onReviewGoalDraft} onSuggest={onSuggestReply}/> : null}
487-
<CollaborationCard request={message.collaboration} />
487+
<CollaborationCards request={message.collaboration} requests={message.collaborations} />
488488
<ReturnDeliveryStatus delivery={message.returnDelivery} />
489489
</div>
490490
</article>

‎apps/presentation/dashboard/src/views/dashboard-page.tsx‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,7 @@ type PersonalManagerMessage = {
550550
endedAt?: number;
551551
returnDelivery?: ChatVisibleMessage["return_delivery"];
552552
collaboration?: ChatVisibleMessage["collaboration"];
553+
collaborations?: ChatVisibleMessage["collaborations"];
553554
reconnect?: boolean;
554555
role: "assistant" | "user";
555556
sourceLabel?: string;
@@ -1629,7 +1630,7 @@ function PersonalGoalHome({
16291630
sourceSessionId: sessionId, sourceCreatedAt: row.created_at,
16301631
role: "assistant" as const,
16311632
agentLabel: "协作回执", sourceLabel: "协作回执", text: visibleAgentMessage(row.text), lines: [],
1632-
returnDelivery: row.return_delivery, collaboration: row.collaboration,
1633+
returnDelivery: row.return_delivery, collaboration: row.collaboration, collaborations: row.collaborations,
16331634
}));
16341635
if (updated !== previous) next = { ...next, [targetContextId]: updated };
16351636
}
@@ -1752,7 +1753,7 @@ function PersonalGoalHome({
17521753
attachments: workspaceImageAttachments(message.attachments),
17531754
id: managerMessageId.current++, lines: [],
17541755
role: message.role === "user" ? "user" : "assistant",
1755-
returnDelivery: message.return_delivery, collaboration: message.collaboration,
1756+
returnDelivery: message.return_delivery, collaboration: message.collaboration, collaborations: message.collaborations,
17561757
replyContext: message.reply_context,
17571758
sourceLabel: message.role === "user" ? undefined : message.role === "error" ? "本地会话记录"
17581759
: contextId === "manager" ? `恢复的${t("header.manager")}会话` : `恢复的 ${sessionLabels.get(message.session_id ?? "") ?? selectedAgent.label} 会话`,
@@ -2504,7 +2505,7 @@ function PersonalGoalHome({
25042505
if (answer) updateConversationMessage(targetContextId, completedMessageId, {
25052506
sourceMessageId: answer.message_id, sourceSessionId: sessionId,
25062507
sourceCreatedAt: answer.created_at,
2507-
collaboration: answer.collaboration, returnDelivery: answer.return_delivery,
2508+
collaboration: answer.collaboration, collaborations: answer.collaborations, returnDelivery: answer.return_delivery,
25082509
});
25092510
if (targetContextId === contextId) void conversationHistory.refresh().catch(() => {});
25102511
}).catch(() => { /* The original conversation remains readable. */ });
@@ -2909,7 +2910,7 @@ function PersonalGoalHome({
29092910
updatedAt: message.updatedAt,
29102911
endedAt: message.endedAt,
29112912
returnDelivery: message.returnDelivery,
2912-
collaboration: message.collaboration,
2913+
collaboration: message.collaboration, collaborations: message.collaborations,
29132914
replyContext: message.replyContext,
29142915
goalDraft: message.goalDraft,
29152916
role: message.role,

0 commit comments

Comments
 (0)