Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat: 工具发到任务里的消息标出来源并可点击跳转 (#5123)

Dash4109c63decce
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
index e23f7c6b0b..6626db577d 100644
--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskPush.test.ts
@@ -150,3 +150,90 @@ describe('shared task metadata uses only its authorized task subscription', () =
expect(__testing.queuedPushesFor(guestA)).toEqual([]);
});
});
+
+describe('shared task guests never see the owner private message sources', () => {
+ const privateOrigin = {
+ kind: 'session',
+ senderSessionId: 'owner-private-task',
+ senderSessionTitle: 'Owner private plan',
+ senderBotId: 'bot-1',
+ senderBotName: 'Cindy',
+ displayText: 'please review',
+ };
+ const message = {
+ clientId: 'm1', sessionId: 'task-a', role: 'user', content: 'please review',
+ agentMeta: {
+ origin: privateOrigin,
+ // Host-internal agent-facing copy used for overflow replay; carries the teammate prefix.
+ agentFacingWireContent: { type: 'user', content: '[来自 Cindy 的补充]\n\nplease review' },
+ },
+ };
+ const privateText = /Cindy|owner-private-task|Owner private plan|bot-1/;
+
+ it('redacts new-message pushes for the guest but keeps them for same-account controllers', async () => {
+ const transport = client();
+ __testing.setActiveClient(transport as never);
+ subscriptions.subscribe(guestA, ['session:task-a']);
+ subscriptions.subscribe('own-task', ['session:task-a']);
+ __testing.forwardPush('local-db:messages:created', { sessionId: 'task-a', message });
+ await vi.advanceTimersByTimeAsync(300);
+ const sent = new Map(transport.sendPush.mock.calls.map((call) => [call[0], call[2]]));
+ expect(sent.get(guestA).message.agentMeta.origin).toEqual({ kind: 'session' });
+ expect(JSON.stringify(sent.get(guestA))).not.toMatch(privateText);
+ expect(sent.get('own-task').message.agentMeta).toEqual(message.agentMeta);
+ });
+
+ it('redacts queued-message sources in input projection pushes for the guest', async () => {
+ const transport = client();
+ __testing.setActiveClient(transport as never);
+ subscriptions.subscribe(guestA, ['session:task-a']);
+ subscriptions.subscribe('own-task', ['session:task-a']);
+ // Teammate interjections carry the sender name in the agent-facing text and
+ // origin.displayText; only the prefix-free persisted body may reach a guest.
+ const interjection = {
+ clientId: 'q1',
+ text: '[来自 Cindy 的补充]\n\nplease review',
+ persistedContent: 'please review',
+ origin: { ...privateOrigin, displayText: '[来自 Cindy 的补充]\n\nplease review' },
+ };
+ const projection = {
+ sessionId: 'task-a',
+ pendingQueue: [
+ interjection,
+ { clientId: 'q2', text: 'from lead', origin: { kind: 'orca', senderLabel: 'Lead', senderSessionId: 'lead-task' } },
+ ],
+ recovery: { kind: 'active-turn', item: { ...interjection, clientId: 'q0' } },
+ };
+ __testing.forwardPush('maker:input:projection', projection);
+ await vi.advanceTimersByTimeAsync(300);
+ const sent = new Map(transport.sendPush.mock.calls.map((call) => [call[0], call[2]]));
+ const guestView = sent.get(guestA);
+ expect(guestView.pendingQueue.map((item: { text: string; origin: unknown }) => [item.text, item.origin])).toEqual([
+ ['please review', { kind: 'session', senderSessionId: '', displayText: 'please review' }],
+ ['from lead', { kind: 'orca', senderLabel: 'Lead' }],
+ ]);
+ expect(guestView.recovery.item.text).toBe('please review');
+ expect(guestView.recovery.item.origin).toEqual({ kind: 'session', senderSessionId: '', displayText: 'please review' });
+ expect(JSON.stringify(guestView)).not.toMatch(/Cindy|owner-private-task|Owner private plan|bot-1|lead-task/);
+ expect(sent.get('own-task')).toEqual(projection);
+ });
+
+ it('redacts message history and queue reads answered to the guest only', () => {
+ const transport = client();
+ __testing.setActiveClient(transport as never);
+ __testing.sendInvokeResultSafe(transport as never, guestA, 'r1', { ok: true, result: [message] }, 'local-db:messages:list', ['task-a']);
+ __testing.sendInvokeResultSafe(transport as never, 'own-task', 'r2', { ok: true, result: [message] }, 'local-db:messages:list', ['task-a']);
+ __testing.sendInvokeResultSafe(transport as never, guestA, 'r3', {
+ ok: true,
+ result: {
+ sessionId: 'task-a',
+ pendingQueue: [{ clientId: 'q1', text: 'x', persistedContent: 'please review', origin: privateOrigin }],
+ },
+ }, 'maker:input:get-projection', ['task-a']);
+ const results = new Map(transport.sendInvokeResult.mock.calls.map((call) => [call[1], call[2]]));
+ expect(results.get('r1').result[0].agentMeta.origin).toEqual({ kind: 'session' });
+ expect(JSON.stringify(results.get('r1'))).not.toMatch(privateText);
+ expect(results.get('r2').result[0].agentMeta.origin).toEqual(privateOrigin);
+ expect(results.get('r3').result.pendingQueue[0].origin).toEqual({ kind: 'session', senderSessionId: '', displayText: 'please review' });
+ });
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 9dc08da84e..a6839f7319 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -99,6 +99,11 @@ import {
} from './remoteBotSessionBoundary.js';
import { getControllerPlatform } from './controllerPlatform';
import { getDeviceLinkInvokeContext, runDeviceLinkInvokeContext } from './invoke-context';
+import {
+ redactInputProjectionForSharedGuest,
+ redactMessageRowForSharedGuest,
+ redactSharedGuestPush,
+} from './sharedTaskMessageOrigin';
import { isSharedTaskPeer, SHARED_TASK_CAPABILITY } from '@cindy/device-link';
import { captureSharedTaskPeer, captureSharedTaskPush, assertSharedTaskInvoke, sharedTaskMetadataTopic, sharedTaskAccessFailure } from './sharedTaskDispatch.js';
import { runAsBackgroundDbRpc } from '../localDb/client/rpcAdmission.js';
@@ -1839,7 +1844,7 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
// on the same relay must still receive its unchanged payload.
let mobilePayload: unknown;
let mobilePayloadReady = false;
- const payloadFor = (dst: string): unknown => {
+ const projectedPayloadFor = (dst: string): unknown => {
if (!subscriptions.controllerSupports(dst, DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1)) return remotePayload;
if (!mobilePayloadReady) {
mobilePayload = projectMobileToolPush(channel, remotePayload);
@@ -1847,6 +1852,11 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
}
return mobilePayload;
};
+ // 共享任务访客只能看见本任务:新消息推送里的来源身份与 invoke 读取同口径脱敏。
+ const payloadFor = (dst: string): unknown => {
+ const projected = projectedPayloadFor(dst);
+ return isSharedTaskPeer(dst) ? redactSharedGuestPush(channel, projected) : projected;
+ };
const historySessionId = readPushSessionId(remotePayload);
const deferred = historySessionId !== null && isDeferredHistoryPush(channel, remotePayload,
(id) => readHistoryToolName(historySessionId, id));
@@ -2929,14 +2939,27 @@ function normalizeInvokeResultForWire(result: InvokeResultPayload): InvokeResult
};
}
+/**
+ * @param sharedTaskGuest 结果发往共享任务访客:消息来源里指向房主其它任务 / 伙伴的身份
+ * 一并脱敏(见 sharedTaskMessageOrigin)。同账号控制端保留完整来源以便跳转。
+ */
function sanitizeMessageInvokeResult(
result: InvokeResultPayload,
channel: string | undefined,
+ sharedTaskGuest = false,
): InvokeResultPayload {
+ const sanitizeRow = (record: Record<string, unknown>): Record<string, unknown> => {
+ const sanitized = sanitizeRemoteMessage(record);
+ return sharedTaskGuest ? redactMessageRowForSharedGuest(sanitized) : sanitized;
+ };
+ if (sharedTaskGuest && result.ok && channel === 'maker:input:get-projection') {
+ const projection = redactInputProjectionForSharedGuest(result.result);
+ return projection === result.result ? result : { ok: true, result: projection };
+ }
if (result.ok && (channel === 'local-db:messages:view' || channel === 'local-db:messages:work-details')) {
const page = result.result as { items?: Array<{ type: string; messages?: unknown[] }>; messages?: unknown[] };
const sanitize = (message: unknown) => message && typeof message === 'object' && !Array.isArray(message)
- ? sanitizeRemoteMessage(message as Record<string, unknown>) : message;
+ ? sanitizeRow(message as Record<string, unknown>) : message;
return { ok: true, result: { ...page,
...(page.messages ? { messages: page.messages.map(sanitize) } : {}),
...(page.items ? { items: mapHistoryViewMessages(page.items as HistoryViewItem<HistoryMessageSource>[],
@@ -2948,7 +2971,7 @@ function sanitizeMessageInvokeResult(
let changed = false;
const sanitized = result.result.map((msg: unknown) => {
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) return msg;
- const out = sanitizeRemoteMessage(msg as Record<string, unknown>);
+ const out = sanitizeRow(msg as Record<string, unknown>);
if (out !== msg) changed = true;
return out;
});
@@ -3013,7 +3036,11 @@ function sendInvokeResultSafe(
fingerprint?: string,
): boolean {
const key = `${src}\u0000${requestId}`;
- const sanitized = sanitizeMessageInvokeResult(normalizeInvokeResultForWire(result), channel);
+ const sanitized = sanitizeMessageInvokeResult(
+ normalizeInvokeResultForWire(result),
+ channel,
+ isSharedTaskPeer(src),
+ );
const normalized = sanitized.ok && channel === 'local-db:sessions:list'
? {
...sanitized,
diff --git a/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts b/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts
new file mode 100644
index 0000000000..c3898ed615
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sharedTaskMessageOrigin.ts
@@ -0,0 +1,112 @@
+import { queueItemVisibleText } from '@cindy/maker-shared/queue';
+
+/**
+ * 共享任务访客只能直接访问被共享的这一个任务(docs/product-rules/shared-task-mode.md)。
+ * 消息来源(agentMeta.origin)里指向房主其它任务或伙伴的身份——来源任务 id、标题、
+ * 伙伴 id / 名字、Orca 发送方任务——都不属于访客可见范围,投递给访客前一律剥掉。
+ * 任务来源降级为不带身份的 `{ kind: 'session' }`,访客端显示不可点击的「由其他任务发送」。
+ *
+ * `agentFacingWireContent` 是主机内部的 Agent 原文副本(只用于上下文溢出后重放),
+ * 可能带「[来自 X 的补充]」这类来源前缀;访客端从不使用,一律不下发。
+ */
+export function redactMessageOriginForSharedGuest(agentMeta: unknown): unknown {
+ if (!agentMeta || typeof agentMeta !== 'object' || Array.isArray(agentMeta)) return agentMeta;
+ const meta = agentMeta as Record<string, unknown>;
+ const { agentFacingWireContent: _wire, ...rest } = meta;
+ const hadWire = 'agentFacingWireContent' in meta;
+ const origin = meta.origin;
+ if (!origin || typeof origin !== 'object' || Array.isArray(origin)) {
+ return hadWire ? rest : agentMeta;
+ }
+ const kind = (origin as { kind?: unknown }).kind;
+ if (kind === 'session') return { ...rest, origin: { kind: 'session' } };
+ if (kind === 'orca' && 'senderSessionId' in origin) {
+ const { senderSessionId: _, ...orcaRest } = origin as Record<string, unknown>;
+ return { ...rest, origin: orcaRest };
+ }
+ return hadWire ? rest : agentMeta;
+}
+
+/** 对单条消息行套用 {@link redactMessageOriginForSharedGuest};无需改动时返回原引用。 */
+export function redactMessageRowForSharedGuest<T>(message: T): T {
+ if (!message || typeof message !== 'object' || Array.isArray(message)) return message;
+ const record = message as Record<string, unknown>;
+ const agentMeta = redactMessageOriginForSharedGuest(record.agentMeta);
+ return agentMeta === record.agentMeta ? message : ({ ...record, agentMeta } as T);
+}
+
+/**
+ * 排队条目的访客视图。任务来源条目里,发给 Agent 的 `text` 与 `origin.displayText`
+ * 可能带来源身份(如伙伴补充的「[来自 X 的补充]」前缀),访客只能拿到落库可见正文
+ * (`persistedContent`,带附件时是 `{text, images, files}` 信封里的 text);来源降级为
+ * 不带 id / 标题 / 伙伴的任务来源。Orca 来源去掉发送方任务 id。无需改动时返回原引用。
+ */
+export function redactQueueItemForSharedGuest<T>(item: T): T {
+ if (!item || typeof item !== 'object' || Array.isArray(item)) return item;
+ const entry = item as Record<string, unknown>;
+ const origin = entry.origin;
+ if (!origin || typeof origin !== 'object' || Array.isArray(origin)) return item;
+ const typed = origin as Record<string, unknown>;
+ if (typed.kind === 'session') {
+ const visible = queueItemVisibleText(entry);
+ return {
+ ...entry,
+ text: visible,
+ origin: { kind: 'session', senderSessionId: '', displayText: visible },
+ } as T;
+ }
+ if (typed.kind === 'orca' && 'senderSessionId' in typed) {
+ const { senderSessionId: _, ...rest } = typed;
+ return { ...entry, origin: rest } as T;
+ }
+ return item;
+}
+
+/**
+ * 排队快照(maker:input:projection 推送 / maker:input:get-projection 读取)的访客视图:
+ * 待发送队列与失败恢复项(`recovery.item`)里的每个条目都经
+ * {@link redactQueueItemForSharedGuest}。无需改动时返回原引用。
+ */
+export function redactInputProjectionForSharedGuest<T>(projection: T): T {
+ if (!projection || typeof projection !== 'object' || Array.isArray(projection)) return projection;
+ const record = projection as Record<string, unknown>;
+ let changed = false;
+ const next: Record<string, unknown> = { ...record };
+ if (Array.isArray(record.pendingQueue)) {
+ const pendingQueue = record.pendingQueue.map((item: unknown) =>
+ redactQueueItemForSharedGuest(item),
+ );
+ if (pendingQueue.some((item, index) => item !== (record.pendingQueue as unknown[])[index])) {
+ next.pendingQueue = pendingQueue;
+ changed = true;
+ }
+ }
+ const recovery = record.recovery;
+ if (recovery && typeof recovery === 'object' && !Array.isArray(recovery) && 'item' in recovery) {
+ const item = (recovery as { item: unknown }).item;
+ const redacted = redactQueueItemForSharedGuest(item);
+ if (redacted !== item) {
+ next.recovery = { ...(recovery as Record<string, unknown>), item: redacted };
+ changed = true;
+ }
+ }
+ return changed ? (next as T) : projection;
+}
+
+/** 推往共享任务访客的单帧 payload:按 channel 套用对应的来源脱敏。 */
+export function redactSharedGuestPush(channel: string, payload: unknown): unknown {
+ if (channel === 'maker:input:projection') return redactInputProjectionForSharedGuest(payload);
+ if (
+ channel !== 'local-db:messages:created' ||
+ !payload ||
+ typeof payload !== 'object' ||
+ !('message' in payload)
+ ) {
+ return payload;
+ }
+ const message = (payload as { message: unknown }).message;
+ const redacted = redactMessageRowForSharedGuest(message);
+ return redacted === message
+ ? payload
+ : { ...(payload as Record<string, unknown>), message: redacted };
+}
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index cd595cb714..e7fe39dbea 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -6161,7 +6161,7 @@ describe('Bot Session task end-to-end runtime', () => {
targetSessionId: started.childSessionId,
clientId: childClientId,
message: `[来自 发起方伙伴 的补充]\n\n${instruction}`,
- persistedContent: `[来自 发起方伙伴 的补充]\n\n${instruction}`,
+ persistedContent: instruction,
}));
const readMessage = (sessionId: string, clientId: string) => h.sqlite!.prepare(
'SELECT role, content, agent_meta AS agentMeta FROM messages WHERE session_id = ? AND client_id = ?',
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 5915de7ee0..382628c715 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -3630,6 +3630,19 @@ describe('AgentInputCoordinator send transaction', () => {
expect(h.onUserEnqueue).not.toHaveBeenCalled();
});
+ it('reports tool-sent session inputs as automatic, not as user intervention', async () => {
+ // 其他任务经工具投递的消息与 Orca 同属自动输入:撤销旧 retry owner,但不按真人介入上报。
+ const h = createHarness();
+ const sid = 'session-origin-automatic';
+ h.coordinator.enqueue(sid, {
+ ...makeItem('q-session', 'follow-up from another task'),
+ origin: { kind: 'session', senderSessionId: 'caller', displayText: 'follow-up from another task' },
+ });
+ await flush();
+ expect(h.onAutomaticEnqueue).toHaveBeenCalledWith(sid);
+ expect(h.onUserEnqueue).not.toHaveBeenCalled();
+ });
+
it('a continuation prompt enqueue is not reported as an unrelated intervention', async () => {
// 中断横幅「继续任务」由 renderer 直发 CONTINUE_AFTER_APP_EXIT_PROMPT, 它**先**经
// enqueue、之后才在 drain 时被认成续跑。无条件作废会把它自己的待续跑记账删掉,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
index a67c995a51..e13f7c6aaa 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
@@ -653,6 +653,62 @@ describe('Orca lead/worker dispatcher', () => {
},
});
});
+ it('records the sending Lead or Worker session so the receiver can link back to it', async () => {
+ const resolveWorkerSessionLink = vi.fn(async () => ({
+ leadSessionId: 'lead-session',
+ workerSessionId: 'worker-session',
+ }));
+ const h = createHarness({ shouldQueueNewTurn: vi.fn(() => true), resolveWorkerSessionLink });
+
+ await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage({
+ targetSessionId: 'target-session',
+ rawContent: 'Implement feature',
+ source: 'lead',
+ senderLabel: 'Lead',
+ workerId: 'worker-1',
+ meta: { source: 'orca', context: 'origin-test' },
+ });
+ await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage({
+ targetSessionId: 'target-session',
+ rawContent: 'Done',
+ source: 'worker',
+ senderLabel: 'Worker',
+ workerId: 'worker-1',
+ meta: { source: 'orca', context: 'origin-test' },
+ });
+
+ expect(resolveWorkerSessionLink).toHaveBeenCalledWith('worker-1');
+ expect(h.queuedItems.map((queued) => queued.origin)).toEqual([
+ expect.objectContaining({ kind: 'orca', senderSessionId: 'lead-session' }),
+ expect.objectContaining({ kind: 'orca', senderSessionId: 'worker-session' }),
+ ]);
+ });
+
+ it('still delivers when the sender session cannot be resolved', async () => {
+ const h = createHarness({
+ shouldQueueNewTurn: vi.fn(() => true),
+ resolveWorkerSessionLink: vi.fn(async () => {
+ throw new Error('db unavailable');
+ }),
+ });
+
+ const result = await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage({
+ targetSessionId: 'target-session',
+ rawContent: 'Implement feature',
+ source: 'lead',
+ senderLabel: 'Lead',
+ workerId: 'worker-1',
+ meta: { source: 'orca', context: 'origin-test' },
+ });
+
+ expect(result).toMatchObject({ ok: true, mode: 'queued' });
+ expect(h.queuedItems[0]?.origin).toEqual({
+ kind: 'orca',
+ senderLabel: 'Lead',
+ displayText: 'Implement feature',
+ });
+ });
+
it('builds the standard Orca queue item and runs the reserve hook at the head boundary', async () => {
const order: string[] = [];
const reserveNextQueuedMessage = vi.fn(async (_sessionId, item, onReserved) => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts
index 30ff62f42c..c723fbbb6b 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts
@@ -170,6 +170,36 @@ describe('session control domain service', () => {
).toBe(explicit);
});
+ it('snapshots the dispatcher title for the receiver source label', () => {
+ expect(
+ sessionQueueOriginForDispatcher({
+ dispatcherSessionId: 'caller',
+ dispatcherSessionTitle: ' Release checklist ',
+ message: 'follow-up',
+ }),
+ ).toEqual({
+ kind: 'session',
+ senderSessionId: 'caller',
+ displayText: 'follow-up',
+ senderSessionTitle: 'Release checklist',
+ });
+ expect(
+ sessionQueueOriginForDispatcher({
+ dispatcherSessionId: 'caller',
+ dispatcherSessionTitle: ' ',
+ message: 'follow-up',
+ }),
+ ).not.toHaveProperty('senderSessionTitle');
+ expect(
+ sessionQueueOriginForDispatcher({
+ dispatcherSessionId: 'bot-task',
+ dispatcherSessionTitle: 'Weekly feedback',
+ dispatcherBot: { id: 'bot-1', name: 'Cindy' },
+ message: 'follow-up',
+ }),
+ ).toMatchObject({ senderBotId: 'bot-1', senderBotName: 'Cindy' });
+ });
+
it('shares queue lifecycle while enforcing sender ownership and preserving identity', async () => {
const { deps, service } = setup();
await expect(
@@ -242,6 +272,24 @@ describe('session control domain service', () => {
},
);
+ it('keeps the host attachment envelope when the sender edits its own attachment item', () => {
+ const queued = item({ kind: 'session', senderSessionId: 'caller', displayText: 'before' });
+ queued.files = [{ name: 'notes.txt', path: '/repo/notes.txt', category: 'file' } as never];
+ queued.persistedContent = JSON.stringify({
+ text: 'before',
+ images: [],
+ files: [{ name: 'notes.txt', path: '/repo/notes.txt' }],
+ });
+
+ const updated = rebuildSessionQueueItem(queued, 'replacement');
+
+ expect(JSON.parse(updated.persistedContent)).toMatchObject({
+ text: 'replacement',
+ files: [{ name: 'notes.txt', path: '/repo/notes.txt' }],
+ });
+ expect(updated.origin).toMatchObject({ kind: 'session', displayText: 'replacement' });
+ });
+
it('keeps renderer composer envelopes intact when rebuilding a non-session queue item', () => {
const queued = item();
queued.persistedContent = JSON.stringify({
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index b1ef17299f..8d857e998b 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -65,6 +65,7 @@ import {
buildMakerUserMessage,
getAgentInputAttachmentBlockType,
getAgentFacingText,
+ isAutomaticInputOriginKind,
normalizeAgentInputClearBoundaryMs,
parseAgentInputToolLoopDetails,
projectionRetryText,
@@ -978,10 +979,9 @@ function isSchedulerOriginItem(item: AgentInputQueuedMessage | null | undefined)
return item?.origin?.kind === 'scheduler';
}
-/** Orca and scheduler inputs are automation, not a fresh human intervention. */
+/** Scheduler / Orca / tool-sent session inputs are automation, not a fresh human intervention. */
function isAutomaticOriginItem(item: AgentInputQueuedMessage | null | undefined): boolean {
- const kind = item?.origin?.kind;
- return kind === 'scheduler' || kind === 'orca';
+ return isAutomaticInputOriginKind(item?.origin?.kind);
}
function isUiContinuationItem(item: AgentInputQueuedMessage): boolean {
@@ -6283,6 +6283,9 @@ export class AgentInputCoordinator {
uuid: active.messageUuid,
...(item.sharedTaskAuthor ? { sharedTaskAuthor: item.sharedTaskAuthor } : {}),
...(item.autoReviewUserText !== undefined ? { autoReviewUserText: item.autoReviewUserText } : {}),
+ // 与 drain 派发落库(makerSendTransaction)同口径:工具 / Orca / 自动化注入的
+ // steer 也要保留来源,接收方才能渲染来源标签。
+ ...(item.origin ? { origin: item.origin } : {}),
sdkSessionId,
delivery: active.delivery,
...(transcriptParentUuid ? { transcriptParentUuid } : {}),
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index f50f11c919..2af5672f75 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -1606,6 +1606,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
message: buildDelegationPrompt(row),
persistedContent: row.objective,
clientId,
+ // 子任务首条消息标出发起委派的父任务,接收方据此渲染可跳转的来源标签。
+ ...(row.parentSessionId ? { dispatcherSessionId: row.parentSessionId } : {}),
onAccepted: async replayed => {
if (replayed) { persistedReplay = true; return; }
const acceptedAt = now();
@@ -2602,8 +2604,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
const requesterName = await requesterDisplayName(caller.botId);
const recovered = await dispatchTrackedInput(row, {
dispatcherSessionId: callerSessionId,
+ // 前缀只给子任务里的 AI 看;界面上的来源由消息的来源标签(伙伴头像 + 名字)表达,
+ // 落库正文不再重复。
message: [`[来自 ${requesterName} 的补充]`, trimmed].join('\n\n'),
- persistedContent: [`[来自 ${requesterName} 的补充]`, trimmed].join('\n\n'),
+ persistedContent: trimmed,
clientId: BOT_DELEGATION_CLIENT_ID.interjection(delegationId, row.runSequence > 1 ? `${row.runSequence}:${token}` : token),
});
const dispatched = recovered.result;
diff --git a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts
index 746b12f26b..e9dc623313 100644
--- a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts
@@ -172,6 +172,13 @@ export interface OrcaInterAgentDispatcherDeps<TSessionMeta> {
beginDirectTurnChangeSet: (sessionId: string, clientId: string) => Promise<void>;
abortDirectTurnChangeSet: (sessionId: string) => void;
resolveWorkerSenderLabel: (workerId: string, fallback: string) => Promise<string>;
+ /**
+ * 反查 worker 所在的 Lead / Worker 会话,给消息来源标签定位发送方会话。
+ * 缺省或查不到时消息仍照常投递,只是来源不可点击跳转。
+ */
+ resolveWorkerSessionLink?: (
+ workerId: string,
+ ) => Promise<{ leadSessionId: string; workerSessionId: string } | null>;
isSessionRunningError: (err: unknown) => boolean;
log?: OrcaInterAgentDispatcherLogger;
}
@@ -358,14 +365,25 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(
return params.senderLabel;
}
};
+ const resolveOrigin = async (): Promise<NonNullable<AgentInputQueuedMessage['origin']>> => {
+ const [senderLabel, senderSessionId] = await Promise.all([
+ resolveSenderLabel(),
+ resolveOrcaSenderSessionId(deps, params),
+ ]);
+ return {
+ kind: 'orca',
+ senderLabel,
+ displayText: params.rawContent,
+ ...(senderSessionId ? { senderSessionId } : {}),
+ };
+ };
const enqueueQueuedMessage = async (logEvent: string): Promise<DispatchOrcaInterAgentMessageResult> => {
const createOpts = await deps.buildCreateOptsForQueuedSession(params.targetSessionId, meta);
const queued = buildQueuedOrcaInterAgentMessage({
clientId,
agentMessageText,
persistedContent,
- rawContent: params.rawContent,
- senderLabel: await resolveSenderLabel(),
+ origin: await resolveOrigin(),
createOpts,
});
if (params.onAccepted) {
@@ -410,11 +428,7 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(
onAccepted: runAccepted,
onAcceptedRollback: params.onAcceptedRollback,
onAcceptedCommit: params.onAcceptedCommit,
- origin: {
- kind: 'orca',
- senderLabel: await resolveSenderLabel(),
- displayText: params.rawContent,
- },
+ origin: await resolveOrigin(),
});
if (result.ok) {
if (result.wakeKind === 'queued') {
@@ -455,7 +469,7 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(
await deps.prepareUnhealthySession?.(params.targetSessionId);
const live = deps.getLiveSession(params.targetSessionId);
if (!live) return null;
- const senderLabel = await resolveSenderLabel();
+ const origin = await resolveOrigin();
const result = await sendPersistedUserMessageToSession(deps, {
session: live,
dbContent: persistedContent,
@@ -463,11 +477,7 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(
clientId,
source: params.meta.source,
context: params.meta.context,
- origin: {
- kind: 'orca',
- senderLabel,
- displayText: params.rawContent,
- },
+ origin,
onAccepted: runAccepted,
});
if (result.dispatched) {
@@ -542,12 +552,17 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(
senderLabel = params.senderLabel;
}
}
+ const senderSessionId = await resolveOrcaSenderSessionId(deps, params);
const queued = buildQueuedOrcaInterAgentMessage({
clientId,
agentMessageText: formatAgentMessage(params.source, params.rawContent, params.workerId),
persistedContent: formatOrcaCommunicationMessage(params.source, params.rawContent),
- rawContent: params.rawContent,
- senderLabel,
+ origin: {
+ kind: 'orca',
+ senderLabel,
+ displayText: params.rawContent,
+ ...(senderSessionId ? { senderSessionId } : {}),
+ },
createOpts,
});
const callbackAlreadyRegistered = queuedOrcaInterAgentAcceptedCallbacks.has(clientId);
@@ -621,6 +636,21 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(
};
}
+/** Lead 发出的消息来源是 Lead 会话,Worker 发出的是 Worker 会话;都以 workerId 反查。 */
+async function resolveOrcaSenderSessionId<TSessionMeta>(
+ deps: OrcaInterAgentDispatcherDeps<TSessionMeta>,
+ params: Pick<DispatchOrcaInterAgentMessageParams, 'source' | 'workerId'>,
+): Promise<string | undefined> {
+ if (!params.workerId || !deps.resolveWorkerSessionLink) return undefined;
+ try {
+ const link = await deps.resolveWorkerSessionLink(params.workerId);
+ if (!link) return undefined;
+ return params.source === 'lead' ? link.leadSessionId : link.workerSessionId;
+ } catch {
+ return undefined;
+ }
+}
+
async function sendPersistedUserMessageToSession<TSessionMeta>(
deps: OrcaInterAgentDispatcherDeps<TSessionMeta>,
params: {
@@ -702,8 +732,7 @@ function buildQueuedOrcaInterAgentMessage(params: {
clientId: string;
agentMessageText: string;
persistedContent: string;
- rawContent: string;
- senderLabel: string;
+ origin: NonNullable<AgentInputQueuedMessage['origin']>;
createOpts: AgentInputCreateOpts;
}): AgentInputQueuedMessage {
const createdAt = new Date().toISOString();
@@ -723,10 +752,6 @@ function buildQueuedOrcaInterAgentMessage(params: {
createdAt,
},
createOpts: params.createOpts,
- origin: {
- kind: 'orca',
- senderLabel: params.senderLabel,
- displayText: params.rawContent,
- },
+ origin: params.origin,
};
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index f1a54c5b9c..210bcea84e 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -112,6 +112,7 @@ import { getDeviceLinkStatus } from '../device-link/index.js';
import type { AgentMeta, Session as RendererSession } from '../../renderer/lib/ccAgent.types';
import {
deriveAutoTitleSeed,
+ isAutomaticInputOriginKind,
normalizeAgentInputClearBoundaryMs,
serializeSessionReferencePayload,
type AgentInputClearBoundaryOpts,
@@ -8806,6 +8807,36 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
: withCindyMakeProjectUse(app.getPath('userData'), session.workDir, dispatch);
}
+ /**
+ * 来源标签用的发送方身份快照:任务标题,以及该任务所属伙伴(有则标签显示伙伴名)。
+ * 读失败只降级为无标题 / 按普通任务显示,不影响投递。
+ */
+ async function readSenderIdentity(
+ sessionId: string | undefined,
+ ): Promise<{ dispatcherSessionTitle?: string | null; dispatcherBot?: { id: string; name: string } | null }> {
+ if (!sessionId) return {};
+ try {
+ const [row] = await getDbClient()
+ .drizzle.select({
+ title: sessions.title,
+ botId: botSessionLinks.botId,
+ botName: botProfiles.displayName,
+ })
+ .from(sessions)
+ .leftJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))
+ .leftJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (!row) return {};
+ return {
+ dispatcherSessionTitle: row.title,
+ dispatcherBot: row.botId ? { id: row.botId, name: row.botName || row.botId } : null,
+ };
+ } catch {
+ return {};
+ }
+ }
+
async function sendToSessionInternal(params: {
targetSessionId?: string;
message: string;
@@ -8846,6 +8877,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
} = params;
const queuedOrigin = sessionQueueOriginForDispatcher({
dispatcherSessionId,
+ ...(await readSenderIdentity(origin ? undefined : dispatcherSessionId)),
message,
explicitOrigin: origin,
});
@@ -9619,6 +9651,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
meta,
files: params.files,
...(params.toolsDisabled === true ? { toolsDisabled: true } : {}),
+ origin: sessionQueueOriginForDispatcher({
+ dispatcherSessionId: params.dispatcherSessionId,
+ ...(await readSenderIdentity(params.dispatcherSessionId)),
+ message: params.message,
+ }),
});
const enqueue = () => inputCoordinator.enqueue(params.targetSessionId, queued, {
resumeRestorePausedQueue: true,
@@ -10391,6 +10428,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const worker = (await listWorkersByLead(link.leadSessionId)).find((w) => w.id === workerId);
return worker?.role ?? fallback;
},
+ resolveWorkerSessionLink: async (workerId) => {
+ const link = await getWorkerLink({ workerId });
+ return link ? { leadSessionId: link.leadSessionId, workerSessionId: link.workerSessionId } : null;
+ },
isSessionRunningError,
log,
});
@@ -12073,7 +12114,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
persistedContent: message,
clientId: queuedMessageId,
meta,
- origin: { kind: 'session', senderSessionId: callerSessionId, displayText: message },
+ origin: sessionQueueOriginForDispatcher({
+ dispatcherSessionId: callerSessionId,
+ ...(await readSenderIdentity(callerSessionId)),
+ message,
+ }),
});
},
steerQueuedMessage: async (sessionId, item, expectedTurn) => {
@@ -12436,11 +12481,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
: undefined;
const originKind =
origin && typeof origin === 'object' ? (origin as { kind?: unknown }).kind : undefined;
- // Scheduler prompts are automatic inputs, not fresh human intervention. They may
- // share the coordinator persistence path with composer messages, but must not recharge
- // the interrupted-turn episode budget and defeat its hard upper bound.
- const isAutomaticPrompt =
- originKind === 'scheduler' || originKind === 'goal' || originKind === 'orca';
+ // Automatic inputs (scheduler / goal / Orca / tool-sent session messages) are not fresh
+ // human intervention. They may share the coordinator persistence path with composer
+ // messages, but must not recharge the interrupted-turn episode budget and defeat its
+ // hard upper bound.
+ const isAutomaticPrompt = isAutomaticInputOriginKind(originKind);
silentStopAutoResumeGuard.noteUserSend(sessionId);
if (!isAutomaticPrompt) interruptedTurnAutoResumeGuard.noteUserSend(sessionId);
}
diff --git a/apps/desktop/src/main/maker-ipc/sessionControlService.ts b/apps/desktop/src/main/maker-ipc/sessionControlService.ts
index 7864806bb6..be260c4a92 100644
--- a/apps/desktop/src/main/maker-ipc/sessionControlService.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionControlService.ts
@@ -314,8 +314,10 @@ export function rebuildSessionQueueItem(
// send_to_session owns raw user text, not a renderer composer envelope.
// A valid JSON object/array is still literal message content, so editing it
// must replace the persisted history row wholesale instead of merging a
- // synthetic `text` property into the old JSON value.
- updated.persistedContent = message;
+ // synthetic `text` property into the old JSON value. Attachment items are
+ // the exception: their persisted row is the host-built `{text, images, files}`
+ // envelope, which updateQueuedMessageText already rewrote in place.
+ if (!item.files?.length) updated.persistedContent = message;
updated.origin = { ...updated.origin, displayText: message };
}
return updated;
@@ -323,14 +325,23 @@ export function rebuildSessionQueueItem(
export function sessionQueueOriginForDispatcher(params: {
dispatcherSessionId?: string;
+ /** 来源会话当前标题快照;缺失时接收方 renderer 回退实时查询或通用文案。 */
+ dispatcherSessionTitle?: string | null;
+ /** 来源会话所属伙伴;有则接收方标签显示「由伙伴「X」发送」。 */
+ dispatcherBot?: { id: string; name: string } | null;
message: string;
explicitOrigin?: AgentInputQueuedMessage['origin'];
}): AgentInputQueuedMessage['origin'] | undefined {
if (params.explicitOrigin) return params.explicitOrigin;
if (!params.dispatcherSessionId) return undefined;
+ const senderSessionTitle = params.dispatcherSessionTitle?.trim();
return {
kind: 'session',
senderSessionId: params.dispatcherSessionId,
displayText: params.message,
+ ...(senderSessionTitle ? { senderSessionTitle } : {}),
+ ...(params.dispatcherBot
+ ? { senderBotId: params.dispatcherBot.id, senderBotName: params.dispatcherBot.name }
+ : {}),
};
}
diff --git a/apps/desktop/src/renderer/__tests__/messageAutomationOrigin.test.ts b/apps/desktop/src/renderer/__tests__/messageAutomationOrigin.test.ts
new file mode 100644
index 0000000000..106144be88
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/messageAutomationOrigin.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import { toMessageAutomationOrigin } from '@/lib/messageAutomationOrigin';
+
+describe('toMessageAutomationOrigin', () => {
+ it('keeps scheduler origins unchanged', () => {
+ const origin = { kind: 'scheduler', scheduleId: 's1', scheduleName: 'Nightly', runId: 'r1' };
+ expect(toMessageAutomationOrigin(origin)).toBe(origin);
+ });
+
+ it('projects tool-sent session origins with the sender title snapshot', () => {
+ expect(
+ toMessageAutomationOrigin({
+ kind: 'session',
+ senderSessionId: 'caller',
+ displayText: 'follow-up',
+ senderSessionTitle: ' Release checklist ',
+ }),
+ ).toEqual({
+ kind: 'session',
+ senderSessionId: 'caller',
+ senderSessionTitle: 'Release checklist',
+ });
+ });
+
+ it('carries the sender teammate identity when the source session belongs to one', () => {
+ expect(
+ toMessageAutomationOrigin({
+ kind: 'session',
+ senderSessionId: 'bot-task',
+ senderSessionTitle: 'Weekly feedback',
+ senderBotId: 'bot-1',
+ senderBotName: 'Cindy',
+ }),
+ ).toEqual({
+ kind: 'session',
+ senderSessionId: 'bot-task',
+ senderSessionTitle: 'Weekly feedback',
+ senderBotId: 'bot-1',
+ senderBotName: 'Cindy',
+ });
+ });
+
+ it('links Orca messages to the sending session only when it was recorded', () => {
+ expect(
+ toMessageAutomationOrigin({ kind: 'orca', senderLabel: 'Lead', senderSessionId: 'lead-1' }),
+ ).toEqual({ kind: 'session', senderSessionId: 'lead-1' });
+ expect(toMessageAutomationOrigin({ kind: 'orca', senderLabel: 'Lead' })).toBeUndefined();
+ });
+
+ it('ignores missing, malformed, and unknown origins', () => {
+ expect(toMessageAutomationOrigin(undefined)).toBeUndefined();
+ expect(toMessageAutomationOrigin('scheduler')).toBeUndefined();
+ expect(toMessageAutomationOrigin({ kind: 'desktop' })).toBeUndefined();
+ });
+
+ it('keeps a generic, non-navigable session origin when the host redacted the sender', () => {
+ expect(toMessageAutomationOrigin({ kind: 'session' })).toEqual({ kind: 'session' });
+ expect(toMessageAutomationOrigin({ kind: 'session', senderSessionId: ' ' })).toEqual({ kind: 'session' });
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts b/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts
index 09fdf2af6a..09b129642a 100644
--- a/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts
+++ b/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts
@@ -62,8 +62,15 @@ describe('deriveNavRailEntries', () => {
automationOrigin: { kind: 'scheduler', scheduleId: 'schedule-1' },
}),
msg({ clientId: 'u3', role: 'user', content: '普通提问', automationOrigin: undefined }),
+ // 其他任务经工具发来的消息不是每轮重复的调度 prompt,保持普通刻度。
+ msg({
+ clientId: 'u4',
+ role: 'user',
+ content: '任务发来',
+ automationOrigin: { kind: 'session', senderSessionId: 'caller' },
+ }),
]);
- expect(entries.map((entry) => entry.isAutomation)).toEqual([false, true, false]);
+ expect(entries.map((entry) => entry.isAutomation)).toEqual([false, true, false, false]);
});
it('运行中插话(delivery=steer)不算新一轮,不产生刻度', () => {
diff --git a/apps/desktop/src/renderer/__tests__/pendingQueueRowPresentation.test.ts b/apps/desktop/src/renderer/__tests__/pendingQueueRowPresentation.test.ts
index 9cc52cc85b..9dd543e94c 100644
--- a/apps/desktop/src/renderer/__tests__/pendingQueueRowPresentation.test.ts
+++ b/apps/desktop/src/renderer/__tests__/pendingQueueRowPresentation.test.ts
@@ -41,6 +41,70 @@ function queuedMessage(patch: Partial<QueuedMessage> = {}): QueuedMessage {
}
describe('getPendingQueueRowPresentation', () => {
+ it('marks messages sent by another session as read-only rows with the sender title', () => {
+ const presentation = getPendingQueueRowPresentation(
+ queuedMessage({
+ text: 'follow-up',
+ persistedContent: 'follow-up',
+ origin: {
+ kind: 'session',
+ senderSessionId: 'caller',
+ displayText: 'follow-up',
+ senderSessionTitle: 'Release checklist',
+ },
+ }),
+ );
+
+ expect(presentation).toMatchObject({
+ isSession: true,
+ isOrca: false,
+ isScheduler: false,
+ senderLabel: 'Release checklist',
+ displayText: 'follow-up',
+ canEdit: false,
+ canSteer: false,
+ });
+ expect(
+ getPendingQueueRowPresentation(
+ queuedMessage({ origin: { kind: 'session', senderSessionId: 'caller', displayText: 'x' } }),
+ ).senderLabel,
+ ).toBeNull();
+ expect(
+ getPendingQueueRowPresentation(
+ queuedMessage({
+ origin: {
+ kind: 'session',
+ senderSessionId: 'bot-task',
+ displayText: 'x',
+ senderSessionTitle: 'Weekly feedback',
+ senderBotId: 'bot-1',
+ senderBotName: 'Cindy',
+ },
+ }),
+ ),
+ ).toMatchObject({ isSession: true, senderLabel: 'Cindy', senderBotId: 'bot-1' });
+ });
+
+ it('shows the message text, not the host envelope, for session items with attachments', () => {
+ const origin = { kind: 'session' as const, senderSessionId: 'caller', displayText: 'see attached' };
+ expect(
+ getPendingQueueRowPresentation(
+ queuedMessage({
+ text: 'see attached',
+ persistedContent: JSON.stringify({ text: 'see attached', images: [], files: [{ name: 'a.txt', path: '/a.txt' }] }),
+ files: [{ name: 'a.txt', path: '/a.txt', category: 'file' } as never],
+ origin,
+ }),
+ ).displayText,
+ ).toBe('see attached');
+ // Without attachments a literal JSON message stays verbatim.
+ expect(
+ getPendingQueueRowPresentation(
+ queuedMessage({ text: '{"text":"x"}', persistedContent: '{"text":"x"}', origin }),
+ ).displayText,
+ ).toBe('{"text":"x"}');
+ });
+
it('uses orca sender and display text while disabling edit and steer actions', () => {
const presentation = getPendingQueueRowPresentation(
queuedMessage({
@@ -56,6 +120,8 @@ describe('getPendingQueueRowPresentation', () => {
expect(presentation).toEqual({
isOrca: true,
isScheduler: false,
+ isSession: false,
+ senderBotId: null,
senderLabel: 'reviewer',
displayText: '请看一下这个结论',
isSyntheticTrigger: false,
@@ -83,6 +149,8 @@ describe('getPendingQueueRowPresentation', () => {
expect(presentation).toEqual({
isOrca: false,
isScheduler: true,
+ isSession: false,
+ senderBotId: null,
senderLabel: 'PR #971 心跳',
displayText: 'PR #971 heartbeat prompt',
isSyntheticTrigger: false,
diff --git a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts
index 59be0a44f7..76e390b576 100644
--- a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts
@@ -868,3 +868,19 @@ describe('remoteProjectsStore pending title preview', () => {
expect(remoteProjectsStore.getMergedRemoteSessions()).toBe(first);
});
});
+
+describe('remote session title index', () => {
+ beforeEach(() => remoteProjectsStore.clear());
+
+ it('resolves titles by id and follows renames pushed by the device', () => {
+ remoteProjectsStore.setDeviceSessions('dev-A', 'A', [mk('a', { title: 'Release checklist' })]);
+ expect(remoteProjectsStore.getSessionTitle('a')).toBe('Release checklist');
+ expect(remoteProjectsStore.getSessionTitle('missing')).toBeNull();
+
+ remoteProjectsStore.setDeviceSessions('dev-A', 'A', [mk('a', { title: 'Renamed' })]);
+ expect(remoteProjectsStore.getSessionTitle('a')).toBe('Renamed');
+
+ remoteProjectsStore.removeDevice('dev-A');
+ expect(remoteProjectsStore.getSessionTitle('a')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts b/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts
index 3920f0366e..1a77c6ef1d 100644
--- a/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts
@@ -34,7 +34,7 @@ describe('SelectionQuoteButton — user message floating action exclusion', () =
);
expect(collapseGuard).not.toContain('inlineQuoteCount === 0');
expect(userMessageSource).toMatch(
- /longMessageCollapsed\s*&&\s*\(automationOrigin \? 'line-clamp-3' : 'line-clamp-10'\)/,
+ /longMessageCollapsed\s*&&\s*\(isScheduledAutomation \? 'line-clamp-3' : 'line-clamp-10'\)/,
);
expect(userMessageSource).toMatch(/\{renderContent\(\n\s+segment\.text,/);
expect(userMessageSource).toContain('!longMessageCollapsed,');
diff --git a/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.ts b/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.ts
index cbadd9de15..6b74e1d96e 100644
--- a/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionsStoreAutoTitlePreview.test.ts
@@ -311,3 +311,22 @@ describe('sessionsStore — 预览必须活过全量刷新', () => {
expect(currentTitle()).toBe('我自己起的名字');
});
});
+
+describe('sessionsStore.getTitleById', () => {
+ it('indexes titles across buckets and refreshes after any bucket write', async () => {
+ await seed(session({ title: 'Release checklist' }));
+ expect(sessionsStore.getTitleById(SESSION_ID)).toBe('Release checklist');
+ expect(sessionsStore.getTitleById('missing')).toBeNull();
+
+ list.mockResolvedValue([session({ title: 'Renamed' })]);
+ await sessionsStore.forceRefresh('active');
+ expect(sessionsStore.getTitleById(SESSION_ID)).toBe('Renamed');
+ });
+
+ it('reflects in-place title patches such as the auto-title preview', async () => {
+ await seed(session());
+ expect(sessionsStore.getTitleById(SESSION_ID)).toBe(DEFAULT_DRAFT_SESSION_TITLE);
+ emitAutoTitlePreview(SESSION_ID, '帮我排查登录失败');
+ expect(sessionsStore.getTitleById(SESSION_ID)).toBe('帮我排查登录失败');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx b/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx
index 839a63f94d..d760f7f33a 100644
--- a/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx
+++ b/apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx
@@ -1,37 +1,117 @@
-import { Timer } from 'lucide-react';
+import { useSyncExternalStore } from 'react';
+import { Send, Timer } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
+import { BotAvatar } from '@/features/bots/BotAvatar';
+import { useBotProfiles } from '@/features/bots/botStore';
import { useSessionNavigationMode } from '@/features/cc-agent/embeddedSessionNavigation';
+import {
+ remoteProjectsStore,
+ useRemoteSessionTitle,
+} from '@/features/device-link/remoteProjectsStore';
+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
import { scheduleFocusPath } from '@/features/scheduler/lib/scheduleSessionBinding';
import type { MessageAutomationOrigin } from '@/lib/ccAgent.types';
+import { sessionsStore } from '@/lib/sessionsStore';
import { cn } from '@/lib/utils';
-/** 自动化来源在 embedded 会话中只展示身份,不拥有跳转主窗口路由的能力。 */
+/**
+ * 来源任务的实时标题:远程任务查所在设备的任务镜像,本机任务查本机任务列表,
+ * 都按 id 索引取值(不随无关任务变化逐条扫描);拿不到返回 null,由调用方回退快照。
+ */
+function useLiveSessionTitle(sessionId: string | undefined, remote: boolean): string | null {
+ const localTitle = useSyncExternalStore(
+ (onChange) => sessionsStore.subscribe(onChange),
+ () => (sessionId && !remote ? sessionsStore.getTitleById(sessionId) : null),
+ );
+ const remoteTitle = useRemoteSessionTitle(remote ? sessionId : undefined);
+ return remote ? remoteTitle : localTitle;
+}
+
+/**
+ * 非用户手动输入的消息来源标签:自动化发送的跳自动化页,其他任务经工具发送的
+ * 跳来源任务。embedded 会话中只展示身份,不拥有跳转主窗口路由的能力。
+ */
export function AutomationOriginBadge({
automationOrigin,
+ hostSessionId,
}: {
automationOrigin: MessageAutomationOrigin;
+ /** 标签所在的任务;远程任务据此把来源任务钉到同一台设备再跳转。 */
+ hostSessionId?: string;
}) {
const { t } = useTranslation();
const navigate = useNavigate();
const navigationMode = useSessionNavigationMode();
+ const senderSessionId =
+ automationOrigin.kind === 'session' ? automationOrigin.senderSessionId : undefined;
+ const botProfiles = useBotProfiles();
+ // 远程任务的来源任务与伙伴资料都在那台设备上,本机同 id 资料不可信(与 BotDirectMessageCard 同口径)。
+ // 粘滞归属:relay 瞬时重连会清空镜像索引,此窗口内仍要把远程任务当远程处理,
+ // 否则来源任务会被当成本机任务打开。
+ const hostDeviceId = getStickySessionDeviceId(hostSessionId);
+ const liveSenderTitle = useLiveSessionTitle(senderSessionId, Boolean(hostDeviceId));
+ const senderBot =
+ automationOrigin.kind === 'session' && automationOrigin.senderBotId
+ ? (() => {
+ const profile = hostDeviceId
+ ? undefined
+ : botProfiles.find((item) => item.id === automationOrigin.senderBotId);
+ return {
+ name: profile?.name || automationOrigin.senderBotName || automationOrigin.senderBotId,
+ avatar: profile?.avatar ?? null,
+ avatarColor: profile?.avatarColor ?? null,
+ };
+ })()
+ : null;
+
+ let label: string;
+ let viewTitle: string;
+ // null:来源身份已被主机脱敏(共享任务访客),只展示不可点击的通用文案。
+ let open: (() => void) | null;
+ if (automationOrigin.kind === 'session') {
+ const targetSessionId = automationOrigin.senderSessionId;
+ const senderTitle = liveSenderTitle ?? automationOrigin.senderSessionTitle;
+ label = senderBot
+ ? t('chat.userMessage.botSentNamed', { name: senderBot.name })
+ : senderTitle
+ ? t('chat.userMessage.sessionSentNamed', { name: senderTitle })
+ : t('chat.userMessage.sessionSent');
+ viewTitle = t('chat.userMessage.sessionViewSource');
+ open = targetSessionId
+ ? () => {
+ // 工具只能在同一台设备的任务之间投递:远程任务的来源任务也在那台设备上。
+ if (hostDeviceId) remoteProjectsStore.pinSessionOrigin(hostDeviceId, targetSessionId);
+ navigate(`/cc-agent/${encodeURIComponent(targetSessionId)}`);
+ }
+ : null;
+ } else {
+ label = automationOrigin.scheduleName
+ ? t('chat.userMessage.automationSentNamed', { name: automationOrigin.scheduleName })
+ : t('chat.userMessage.automationSent');
+ viewTitle = t('chat.userMessage.automationViewTask');
+ open = () => navigate(scheduleFocusPath(automationOrigin.scheduleId));
+ }
+
+ const Icon = automationOrigin.kind === 'session' ? Send : Timer;
const content = (
<>
- <Timer size={11} strokeWidth={1.75} aria-hidden className="shrink-0" />
- <span className="min-w-0 truncate">
- {automationOrigin.scheduleName
- ? t('chat.userMessage.automationSentNamed', {
- name: automationOrigin.scheduleName,
- })
- : t('chat.userMessage.automationSent')}
- </span>
+ {senderBot ? (
+ <BotAvatar bot={senderBot} size="xs" className="h-3.5 w-3.5 text-10" />
+ ) : (
+ <Icon size={11} strokeWidth={1.75} aria-hidden className="shrink-0" />
+ )}
+ <span className="min-w-0 truncate">{label}</span>
</>
);
- if (navigationMode === 'sidebar-embedded') {
+ if (navigationMode === 'sidebar-embedded' || !open) {
return (
- <span className="inline-flex max-w-full items-center gap-1 text-11 text-[var(--cmd-palette-item-meta)]">
+ <span
+ data-message-origin={senderBot ? 'bot' : automationOrigin.kind}
+ className="inline-flex max-w-full items-center gap-1 text-11 text-[var(--cmd-palette-item-meta)]"
+ >
{content}
</span>
);
@@ -41,8 +121,9 @@ export function AutomationOriginBadge({
<button
type="button"
data-split-pane-route-action=""
- title={t('chat.userMessage.automationViewTask')}
- onClick={() => navigate(scheduleFocusPath(automationOrigin.scheduleId))}
+ data-message-origin={senderBot ? 'bot' : automationOrigin.kind}
+ title={viewTitle}
+ onClick={open}
className={cn(
'inline-flex max-w-full items-center gap-1 cursor-pointer',
'text-11 text-[var(--cmd-palette-item-meta)]',
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 8320603914..0474b0f927 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -1122,7 +1122,9 @@ export function UserMessage({
// 视觉行数,窗口缩放 / 侧栏开合导致气泡宽度变化时由 ResizeObserver 重算。
// 自动化任务注入的消息(模板化调度 prompt,每轮重复出现)用更低的收起
// 阈值,收起后也只留 3 行(手打消息 14 行阈值 / 收起留 10 行不变)。
- const collapseThreshold = automationOrigin
+ // 其他任务经工具发来的消息不是每轮重复的模板,保持手打消息的收起口径。
+ const isScheduledAutomation = automationOrigin?.kind === 'scheduler';
+ const collapseThreshold = isScheduledAutomation
? AUTOMATION_USER_MESSAGE_VISUAL_LINE_THRESHOLD
: LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD;
// 粘贴段在气泡展示正文(displayBubbleBody)局部坐标下的 range(与下方
@@ -1451,39 +1453,45 @@ export function UserMessage({
>
{sharedAuthorName && <span className="text-12 text-[var(--text-secondary)]">{sharedAuthorName}</span>}
{orcaCommunication ? (
- <div
- className={cn(
- 'w-full rounded-[8px] border border-[var(--msg-tool-card-border)]',
- 'bg-[var(--msg-tool-card-bg)] text-[var(--msg-tool-card-text)]',
- 'overflow-hidden',
+ <>
+ {/* Orca 卡片标题只说明 Lead / Worker 角色;来源标签补上可跳转的发送方任务。 */}
+ {automationOrigin && (
+ <AutomationOriginBadge automationOrigin={automationOrigin} hostSessionId={sessionId} />
)}
- >
- <button
- type="button"
+ <div
className={cn(
- 'flex w-full items-center gap-2 px-3 py-2 text-left',
- 'text-13 font-medium leading-none',
- 'hover:bg-[var(--cmd-palette-item-hover)] transition-colors',
+ 'w-full rounded-[8px] border border-[var(--msg-tool-card-border)]',
+ 'bg-[var(--msg-tool-card-bg)] text-[var(--msg-tool-card-text)]',
+ 'overflow-hidden',
)}
- aria-expanded={orcaExpanded}
- onClick={() => setOrcaExpanded((value) => !value)}
>
- <Bot size={14} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
- <span className="min-w-0 flex-1 truncate">{orcaCardTitle}</span>
- {orcaExpanded ? (
- <ChevronDown size={14} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
- ) : (
- <ChevronRight size={14} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
+ <button
+ type="button"
+ className={cn(
+ 'flex w-full items-center gap-2 px-3 py-2 text-left',
+ 'text-13 font-medium leading-none',
+ 'hover:bg-[var(--cmd-palette-item-hover)] transition-colors',
+ )}
+ aria-expanded={orcaExpanded}
+ onClick={() => setOrcaExpanded((value) => !value)}
+ >
+ <Bot size={14} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
+ <span className="min-w-0 flex-1 truncate">{orcaCardTitle}</span>
+ {orcaExpanded ? (
+ <ChevronDown size={14} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
+ ) : (
+ <ChevronRight size={14} className="shrink-0 text-[var(--msg-tool-card-chevron)]" />
+ )}
+ </button>
+ {orcaExpanded && (
+ <div className="border-t border-[var(--msg-tool-card-border)] px-3 py-2">
+ <pre className="m-0 whitespace-pre-wrap break-words font-mono text-[length:calc(var(--app-code-font-size)_-_2px)] leading-[calc(var(--app-code-font-size)_+_4px)] text-[var(--foreground)]">
+ {displayContent}
+ </pre>
+ </div>
)}
- </button>
- {orcaExpanded && (
- <div className="border-t border-[var(--msg-tool-card-border)] px-3 py-2">
- <pre className="m-0 whitespace-pre-wrap break-words font-mono text-[length:calc(var(--app-code-font-size)_-_2px)] leading-[calc(var(--app-code-font-size)_+_4px)] text-[var(--foreground)]">
- {displayContent}
- </pre>
- </div>
- )}
- </div>
+ </div>
+ </>
) : hookSource && !editing ? (
<>
{/* hook 消息: Cindy 署名任务卡片(左对齐), 替代右对齐用户气泡 +
@@ -1504,10 +1512,13 @@ export function UserMessage({
</>
) : (
<>
- {/* 自动化任务注入的消息:气泡上方右对齐渲染来源标签(不进气泡、不入 copyText)。
- 点击跳转自动化页并 focus 对应条目(与侧边栏自动化分组"编辑"同款 query
- 机制);任务已删除时 SchedulerPage 的 focus 兜底会自动回退到列表首条。 */}
- {automationOrigin && <AutomationOriginBadge automationOrigin={automationOrigin} />}
+ {/* 自动化 / 其他任务注入的消息:气泡上方右对齐渲染来源标签(不进气泡、不入
+ copyText)。自动化来源跳转自动化页并 focus 对应条目(与侧边栏自动化分组"编辑"
+ 同款 query 机制;已删除时 SchedulerPage 的 focus 兜底回退到列表首条);
+ 任务来源跳转发送方任务。 */}
+ {automationOrigin && (
+ <AutomationOriginBadge automationOrigin={automationOrigin} hostSessionId={sessionId} />
+ )}
{/* /goal 目标设定/更新:气泡上方右对齐渲一个徽标(不进气泡、不入 copyText)。 */}
{goalBadge && (
<span
@@ -1621,7 +1632,7 @@ export function UserMessage({
className={cn(
'min-w-0 whitespace-pre-wrap [overflow-wrap:anywhere]',
longMessageCollapsed &&
- (automationOrigin ? 'line-clamp-3' : 'line-clamp-10'),
+ (isScheduledAutomation ? 'line-clamp-3' : 'line-clamp-10'),
)}
>
{quoteSegments.map((segment, index) =>
@@ -1699,7 +1710,7 @@ export function UserMessage({
className={cn(
'whitespace-pre-wrap [overflow-wrap:anywhere]',
longMessageCollapsed &&
- (automationOrigin ? 'line-clamp-3' : 'line-clamp-10'),
+ (isScheduledAutomation ? 'line-clamp-3' : 'line-clamp-10'),
)}
>
{longMessageCollapsed
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/AutomationOriginBadge.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/AutomationOriginBadge.test.tsx
new file mode 100644
index 0000000000..4c249502eb
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/AutomationOriginBadge.test.tsx
@@ -0,0 +1,75 @@
+// @vitest-environment jsdom
+
+import { fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ navigate: vi.fn() }));
+
+vi.mock('react-router-dom', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('react-router-dom')>();
+ return { ...actual, useNavigate: () => mocks.navigate };
+});
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, values?: { name?: string }) => (values?.name ? `${key}:${values.name}` : key),
+ }),
+}));
+
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import {
+ __resetStickySessionOriginForTest,
+ getStickySessionDeviceId,
+} from '@/features/device-link/stickySessionOrigin';
+import type { Session } from '@/lib/ccAgent.types';
+
+import { AutomationOriginBadge } from '../AutomationOriginBadge';
+
+function remoteSession(id: string): Session {
+ return {
+ id,
+ title: id,
+ status: 'active',
+ workingDir: '/repo',
+ workspaceKind: 'project',
+ } as Session;
+}
+
+afterEach(() => {
+ remoteProjectsStore.clear();
+ __resetStickySessionOriginForTest();
+ mocks.navigate.mockReset();
+});
+
+describe('AutomationOriginBadge', () => {
+ it('keeps a remote host task remote while the relay mirror is being rebuilt', () => {
+ remoteProjectsStore.setDeviceSessions('dev-A', 'A', [remoteSession('host-task')]);
+ // The session view has already resolved (and cached) this task as remote.
+ expect(getStickySessionDeviceId('host-task')).toBe('dev-A');
+ // Relay reconnect: the live registry is cleared before the snapshot returns.
+ remoteProjectsStore.clear();
+ const pin = vi.spyOn(remoteProjectsStore, 'pinSessionOrigin');
+
+ render(
+ <AutomationOriginBadge
+ automationOrigin={{
+ kind: 'session',
+ senderSessionId: 'source-task',
+ senderSessionTitle: 'Source',
+ }}
+ hostSessionId="host-task"
+ />,
+ );
+ fireEvent.click(screen.getByRole('button'));
+
+ expect(pin).toHaveBeenCalledWith('dev-A', 'source-task');
+ expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/source-task');
+ });
+
+ it('renders a redacted shared-task source as static text', () => {
+ render(
+ <AutomationOriginBadge automationOrigin={{ kind: 'session' }} hostSessionId="guest-task" />,
+ );
+ expect(screen.queryByRole('button')).toBeNull();
+ expect(screen.getByText('chat.userMessage.sessionSent')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx
index fbd75d9c82..f0a9bea01b 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx
@@ -36,6 +36,12 @@ vi.mock('react-i18next', () => ({
}));
vi.mock('@/features/device-link/remoteProjectsStore', () => ({
useRemoteProjectSessions: () => [],
+ useRemoteSessionTitle: () => null,
+ getSessionDeviceId: () => undefined,
+ remoteProjectsStore: {
+ getSessionDeviceId: () => undefined,
+ pinSessionOrigin: () => undefined,
+ },
}));
vi.mock('@/lib/sessionService', () => ({ get: mocks.getSession }));
vi.mock('@/lib/sessionMessageText', () => ({
diff --git a/apps/desktop/src/renderer/components/chat/messageNavRailModel.ts b/apps/desktop/src/renderer/components/chat/messageNavRailModel.ts
index d9fa9dcb25..7b91305429 100644
--- a/apps/desktop/src/renderer/components/chat/messageNavRailModel.ts
+++ b/apps/desktop/src/renderer/components/chat/messageNavRailModel.ts
@@ -197,7 +197,11 @@ export function deriveNavRailEntries(messages: readonly ChatMessage[]): NavRailE
const attachmentCount = (m.images?.length ?? 0) + (m.files?.length ?? 0);
if (preview) {
closeAnswerTurn();
- entries.push({ id: m.clientId, preview, isAutomation: Boolean(m.automationOrigin) });
+ entries.push({
+ id: m.clientId,
+ preview,
+ isAutomation: m.automationOrigin?.kind === 'scheduler',
+ });
lastOwnsAnswers = true;
} else if (attachmentCount > 0) {
// 有附件但一个名字都取不到(粘贴截图):仍是真实提问,保留刻度,
@@ -207,7 +211,7 @@ export function deriveNavRailEntries(messages: readonly ChatMessage[]): NavRailE
id: m.clientId,
preview: '',
attachmentsOnly: attachmentCount,
- isAutomation: Boolean(m.automationOrigin),
+ isAutomation: m.automationOrigin?.kind === 'scheduler',
});
lastOwnsAnswers = true;
} else {
diff --git a/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx b/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx
index 95174e51ac..ecaf5c823f 100644
--- a/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx
@@ -29,6 +29,7 @@ import {
ChevronUp,
GripVertical,
Pencil,
+ Send,
Trash2,
} from 'lucide-react';
import type { KeyboardEvent as ReactKeyboardEvent, ReactElement } from 'react';
@@ -39,6 +40,8 @@ import { SortableList } from '@/components/sidebar/SortableList';
import { SentInlineAtomBody } from '@/components/chat/SentInlineAtomBody';
import { Spinner } from '@/components/ui/spinner';
import { Tip } from '@/components/ui/tooltip';
+import { BotAvatar } from '@/features/bots/BotAvatar';
+import { useBotProfiles } from '@/features/bots/botStore';
import { cn } from '@/lib/utils';
import type { QueuedMessage } from '@/lib/makerChatStore';
import {
@@ -163,6 +166,7 @@ export function PendingQueuePanel({
turnRunning = false,
}: PendingQueuePanelProps): ReactElement | null {
const { t } = useTranslation();
+ const botProfiles = useBotProfiles();
const resolvedAriaLabel = ariaLabel ?? t('newChat.pendingQueue.regionAria');
const [rowActivity, setRowActivity] = useState(emptyPendingQueueRowActivityState);
const editingLockOwnerRef = useRef<QueueEditLockOwner | null>(null);
@@ -291,6 +295,13 @@ export function PendingQueuePanel({
className="pending-queue-scroll flex max-h-[196px] flex-col gap-0 overflow-y-auto overscroll-contain px-1 pb-0.5 pt-1.5 [scrollbar-gutter:stable_both-edges]"
renderItem={(entry, originalIdx) => {
const rowPresentation = getPendingQueueRowPresentation(entry);
+ const senderBotProfile = rowPresentation.senderBotId
+ ? botProfiles.find((item) => item.id === rowPresentation.senderBotId)
+ : undefined;
+ const queueRowSenderLabel =
+ senderBotProfile?.name ||
+ rowPresentation.senderLabel ||
+ (rowPresentation.isSession ? t('newChat.pendingQueue.sessionSenderFallback') : null);
const isPendingEnqueue = entry.isPendingEnqueue === true;
const isRowActive = isPendingQueueRowActive(rowActivity, entry.clientId);
const isRowEditing = entry.clientId === editingClientId;
@@ -453,17 +464,38 @@ export function PendingQueuePanel({
>
<GripVertical size={12} strokeWidth={2} aria-hidden />
</button>
- {rowPresentation.isOrca || rowPresentation.isScheduler ? (
+ {rowPresentation.isOrca || rowPresentation.isScheduler || rowPresentation.isSession ? (
<div
aria-label={t(
rowPresentation.isScheduler
? 'newChat.pendingQueue.schedulerRowAria'
- : 'newChat.pendingQueue.orcaRowAria',
- { sender: rowPresentation.senderLabel },
+ : rowPresentation.senderBotId
+ ? 'newChat.pendingQueue.botRowAria'
+ : rowPresentation.isSession
+ ? 'newChat.pendingQueue.sessionRowAria'
+ : 'newChat.pendingQueue.orcaRowAria',
+ { sender: queueRowSenderLabel },
)}
className="relative top-px flex min-w-0 flex-1 items-center gap-1.5"
>
- {rowPresentation.isScheduler ? (
+ {rowPresentation.senderBotId ? (
+ <BotAvatar
+ bot={{
+ name: queueRowSenderLabel ?? rowPresentation.senderBotId,
+ avatar: senderBotProfile?.avatar ?? null,
+ avatarColor: senderBotProfile?.avatarColor ?? null,
+ }}
+ size="xs"
+ className="h-3.5 w-3.5 text-10"
+ />
+ ) : rowPresentation.isSession ? (
+ <Send
+ size={13}
+ strokeWidth={2}
+ aria-hidden
+ className="shrink-0 text-[var(--msg-assistant-text)]"
+ />
+ ) : rowPresentation.isScheduler ? (
<AlarmClock
size={13}
strokeWidth={2}
@@ -479,7 +511,7 @@ export function PendingQueuePanel({
/>
)}
<span className="min-w-0 max-w-[120px] shrink truncate text-13 font-semibold leading-[1.25] text-[var(--msg-assistant-text)]">
- {rowPresentation.senderLabel}
+ {queueRowSenderLabel}
</span>
<span
className={cn(
diff --git a/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts b/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts
index f5ac05899d..6345544c42 100644
--- a/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts
+++ b/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts
@@ -1,3 +1,4 @@
+import { queueItemVisibleText } from '@cindy/maker-shared/queue';
import { UI_ACTION_TRIGGER_PREFIX, type QueuedMessage } from '@/lib/makerChatStore';
import { stripChatQuoteMarkerLines } from '@/lib/chatQuotes';
import {
@@ -13,7 +14,15 @@ export interface PendingQueueRowPresentation {
* 一眼看出"这是排队等待的自动化任务"。
*/
isScheduler: boolean;
+ /**
+ * 另一个任务经工具(send_to_session / 伙伴委派等)排进来的消息:同属机器生成,
+ * 保留重排/删除、禁止编辑/steer(改写后气泡的来源标签就不再属实);行首显示来源任务。
+ */
+ isSession: boolean;
+ /** 来源名称;任务来源缺标题快照时为 null,面板显示通用文案。 */
senderLabel: string | null;
+ /** 任务来源属于伙伴时的伙伴 id:面板行首显示伙伴头像,来源名为伙伴名。 */
+ senderBotId: string | null;
displayText: string;
canEdit: boolean;
canSteer: boolean;
@@ -37,7 +46,8 @@ export interface PendingQueueRowPresentation {
* Resolves row-level presentation and permissions for the pending queue.
* Orca messages are generated by another agent, so they keep reorder/remove
* affordances but cannot be edited or steered like a local user draft.
- * Scheduler heartbeat prompts follow the same machine-generated rules; their
+ * Scheduler heartbeat prompts and messages sent by another session through a
+ * tool follow the same machine-generated rules; scheduler
* display text uses persistedContent (the raw schedule prompt) so the hidden
* silent-run protocol suffix in `text` never surfaces in the queue panel.
*/
@@ -45,6 +55,8 @@ export function getPendingQueueRowPresentation(entry: QueuedMessage): PendingQue
const origin = entry.origin;
const isOrca = origin?.kind === 'orca';
const isScheduler = origin?.kind === 'scheduler';
+ const isSession = origin?.kind === 'session';
+ const isMachineGenerated = isOrca || isScheduler || isSession;
const isSyntheticTrigger = entry.text.startsWith(UI_ACTION_TRIGGER_PREFIX);
const isContinueTrigger =
entry.text === CONTINUE_AFTER_APP_EXIT_PROMPT || entry.text === CONTINUE_AFTER_ERROR_PROMPT;
@@ -53,16 +65,26 @@ export function getPendingQueueRowPresentation(entry: QueuedMessage): PendingQue
return {
isOrca,
isScheduler,
- senderLabel: isOrca ? origin.senderLabel : isScheduler ? origin.scheduleName : null,
+ isSession,
+ senderLabel: isOrca
+ ? origin.senderLabel
+ : isScheduler
+ ? origin.scheduleName
+ : isSession
+ ? (origin.senderBotId ? origin.senderBotName?.trim() : undefined) ||
+ origin.senderSessionTitle?.trim() ||
+ null
+ : null,
+ senderBotId: isSession ? (origin.senderBotId ?? null) : null,
displayText: isOrca
? (origin.displayText ?? entry.text)
- : isScheduler
- ? entry.persistedContent || entry.text
+ : isScheduler || isSession
+ ? queueItemVisibleText(entry)
: entry.chatMessage.quotesEncoded === true
? stripChatQuoteMarkerLines(entry.text)
: entry.text,
- canEdit: !isPendingEnqueue && !isOrca && !isScheduler && !isSyntheticTrigger,
- canSteer: !isPendingEnqueue && !isOrca && !isScheduler && !isSyntheticTrigger,
+ canEdit: !isPendingEnqueue && !isMachineGenerated && !isSyntheticTrigger,
+ canSteer: !isPendingEnqueue && !isMachineGenerated && !isSyntheticTrigger,
isSyntheticTrigger,
syntheticKind: isSyntheticTrigger ? (isContinueTrigger ? 'continue' : 'generic') : null,
};
diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
index a93e3e41f1..e5eb509586 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
@@ -157,6 +157,8 @@ let bootstrapRetryImpl: ((deviceId: string) => void) | null = null;
let mergedSnapshot: Session[] = [];
/** sessionId → deviceId 注册表(随分片变化重建)。 */
const sessionDeviceIndex = new Map<string, string>();
+/** sessionId → 投影后标题(含标题预览),随 recompute 重建;供消息来源标签 O(1) 查询。 */
+const sessionTitleIndex = new Map<string, string>();
/**
* 「归属已确定、但快照还没到」的 origin 钉子:sessionId → deviceId。
*
@@ -334,6 +336,7 @@ function withPendingTitle(session: Session): Session {
function recompute(): void {
recomputeScheduleIndex();
sessionDeviceIndex.clear();
+ sessionTitleIndex.clear();
// 先铺 origin 钉子:分片还没到的新建远程会话也必须能被判定为远程(见 pinnedOrigins)。
// 分片派生值随后覆盖同 id 的条目。
for (const [sessionId, deviceId] of pinnedOrigins) sessionDeviceIndex.set(sessionId, deviceId);
@@ -343,8 +346,10 @@ function recompute(): void {
const flat: Session[] = [];
for (const shard of shards.values()) {
for (const s of shard.sessions) {
- flat.push(withPendingTitle(s));
+ const projected = withPendingTitle(s);
+ flat.push(projected);
sessionDeviceIndex.set(s.id, shard.deviceId);
+ if (projected.title) sessionTitleIndex.set(s.id, projected.title);
}
}
mergedSnapshot = flat;
@@ -993,6 +998,11 @@ const actions = {
subs.forEach((fn) => fn());
},
+ /** 远端任务当前标题(含标题预览),按 id 索引;未知任务返回 null。 */
+ getSessionTitle(sessionId: string): string | null {
+ return sessionTitleIndex.get(sessionId)?.trim() || null;
+ },
+
/**
* origin 判定:给定 sessionId 返回其所属被控设备 deviceId;本地会话返回 undefined。
* 传输层 / SessionView / 消息分页据此决定走本机 IPC 还是 deviceLink 隧道。
@@ -1151,6 +1161,13 @@ export function retryRemoteSessionBootstrap(deviceId: string): void {
bootstrapRetryImpl?.(deviceId);
}
+/** 组件内订阅:单个远端任务的当前标题(按 id 索引,不随其它任务变化而扫描列表)。 */
+export function useRemoteSessionTitle(sessionId: string | undefined): string | null {
+ return useSyncExternalStore(subscribe, () =>
+ sessionId ? actions.getSessionTitle(sessionId) : null,
+ );
+}
+
/** 组件内订阅:返回扁平远端会话快照(喂给 sidebar 合并点)。 */
export function useRemoteProjectSessions(): Session[] {
return useSyncExternalStore(subscribe, actions.getMergedRemoteSessions);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 0e737077c5..ced085aa0b 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8579,6 +8579,9 @@
"noTextContent": "(no text content)",
"orcaRowAria": "Queued collaboration message from {{sender}}",
"schedulerRowAria": "Queued automation task message from {{sender}}",
+ "sessionRowAria": "Queued message from session \"{{sender}}\"",
+ "sessionSenderFallback": "Another session",
+ "botRowAria": "Queued message from teammate \"{{sender}}\"",
"dragAria": "Drag queued message {{index}} to reorder",
"steerAction": "Steer",
"steerRunningTip": "Steer this message into the running task without interrupting it; handled once the current action finishes",
@@ -9617,6 +9620,10 @@
"automationSent": "Sent by automation",
"automationSentNamed": "Sent by automation \"{{name}}\"",
"automationViewTask": "View automation task",
+ "sessionSent": "Sent by another session",
+ "sessionSentNamed": "Sent by session \"{{name}}\"",
+ "sessionViewSource": "View source session",
+ "botSentNamed": "Sent by teammate \"{{name}}\"",
"orcaFromLead": "Message from Lead",
"orcaFromWorker": "Message from Worker",
"expandLongMessage": "Show full message",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c03582817a..beaebf0f79 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8577,6 +8577,9 @@
"noTextContent": "(テキストなし)",
"orcaRowAria": "{{sender}} からの協同キュー内メッセージ",
"schedulerRowAria": "自動化タスク「{{sender}}」のキュー内メッセージ",
+ "sessionRowAria": "セッション「{{sender}}」からのキュー内メッセージ",
+ "sessionSenderFallback": "別のセッション",
+ "botRowAria": "仲間「{{sender}}」からのキュー内メッセージ",
"dragAria": "キューの {{index}} 番目のメッセージをドラッグして並べ替え",
"steerAction": "割り込み",
"steerRunningTip": "実行中のタスクを中断せずに割り込み送信します。現在の操作が完了した後に優先して処理されます",
@@ -9611,6 +9614,10 @@
"automationSent": "自動化タスクから送信",
"automationSentNamed": "自動化タスク「{{name}}」から送信",
"automationViewTask": "自動化タスクを表示",
+ "sessionSent": "別のセッションから送信",
+ "sessionSentNamed": "セッション「{{name}}」から送信",
+ "sessionViewSource": "送信元のセッションを表示",
+ "botSentNamed": "仲間「{{name}}」から送信",
"orcaFromLead": "Lead からのメッセージ",
"orcaFromWorker": "Worker からのメッセージ",
"expandLongMessage": "全文を表示",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 376e366988..9e54cb6e05 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8577,6 +8577,9 @@
"noTextContent": "(텍스트 내용 없음)",
"orcaRowAria": "{{sender}}의 협업 대기 메시지",
"schedulerRowAria": "자동화 작업 “{{sender}}”의 대기 메시지",
+ "sessionRowAria": "세션 \"{{sender}}\"에서 온 대기 메시지",
+ "sessionSenderFallback": "다른 세션",
+ "botRowAria": "동료 \"{{sender}}\"에서 온 대기 메시지",
"dragAria": "큐의 {{index}}번째 메시지를 드래그해 순서 변경",
"steerAction": "끼어들기",
"steerRunningTip": "실행 중인 작업을 중단하지 않고 끼어듭니다. 현재 동작이 끝난 후 이 메시지를 우선 처리합니다",
@@ -9611,6 +9614,10 @@
"automationSent": "자동화 작업에서 보냄",
"automationSentNamed": "자동화 작업 \"{{name}}\"에서 보냄",
"automationViewTask": "자동화 작업 보기",
+ "sessionSent": "다른 세션에서 보냄",
+ "sessionSentNamed": "세션 \"{{name}}\"에서 보냄",
+ "sessionViewSource": "보낸 세션 보기",
+ "botSentNamed": "동료 \"{{name}}\"에서 보냄",
"orcaFromLead": "Lead에서 온 메시지",
"orcaFromWorker": "Worker에서 온 메시지",
"expandLongMessage": "전체 메시지 보기",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 73ce60d07d..0b803bdc50 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8577,6 +8577,9 @@
"noTextContent": "(无文本内容)",
"orcaRowAria": "来自协同 {{sender}} 的排队消息",
"schedulerRowAria": "自动化「{{sender}}」的排队消息",
+ "sessionRowAria": "任务「{{sender}}」发来的排队消息",
+ "sessionSenderFallback": "其他任务",
+ "botRowAria": "伙伴「{{sender}}」发来的排队消息",
"dragAria": "拖动第 {{index}} 条待发送消息排序",
"steerAction": "插话",
"steerRunningTip": "插话到当前任务,不打断正在执行的工作,当前动作完成后优先处理这条消息",
@@ -9611,6 +9614,10 @@
"automationSent": "由自动化发送",
"automationSentNamed": "由自动化「{{name}}」发送",
"automationViewTask": "查看自动化",
+ "sessionSent": "由其他任务发送",
+ "sessionSentNamed": "由任务「{{name}}」发送",
+ "sessionViewSource": "查看来源任务",
+ "botSentNamed": "由伙伴「{{name}}」发送",
"orcaFromLead": "来自 Lead 的消息",
"orcaFromWorker": "来自 Worker 的消息",
"expandLongMessage": "展开全文",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 2b9eef91ba..4d9b21535e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8577,6 +8577,9 @@
"noTextContent": "(無文字內容)",
"orcaRowAria": "來自協同 {{sender}} 的排隊訊息",
"schedulerRowAria": "自動化「{{sender}}」的排隊訊息",
+ "sessionRowAria": "任務「{{sender}}」傳來的排隊訊息",
+ "sessionSenderFallback": "其他任務",
+ "botRowAria": "夥伴「{{sender}}」傳來的排隊訊息",
"dragAria": "拖動第 {{index}} 條待傳送訊息排序",
"steerAction": "插話",
"steerRunningTip": "插話到當前任務,不打斷正在執行的工作,當前動作完成後優先處理這條訊息",
@@ -9610,6 +9613,10 @@
"automationSent": "由自動化傳送",
"automationSentNamed": "由自動化「{{name}}」傳送",
"automationViewTask": "檢視自動化",
+ "sessionSent": "由其他任務傳送",
+ "sessionSentNamed": "由任務「{{name}}」傳送",
+ "sessionViewSource": "檢視來源任務",
+ "botSentNamed": "由夥伴「{{name}}」傳送",
"orcaFromLead": "來自 Lead 的訊息",
"orcaFromWorker": "來自 Worker 的訊息",
"expandLongMessage": "展開全文",
diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.ts
index d566f007cb..912bf96a26 100644
--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts
+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts
@@ -34,13 +34,43 @@ export type NativeForkAnchor = {
* 而非用户手动输入。scheduler runner 落库时写入 agentMeta.origin,
* renderer 据此在气泡上渲染"由自动化任务发送"标签。
*/
-export interface MessageAutomationOrigin {
+export interface MessageSchedulerOrigin {
kind: 'scheduler';
scheduleId: string;
scheduleName?: string;
runId?: string;
}
+/**
+ * 另一个任务经工具(send_to_session / steer_session / 伙伴委派 / Orca 协同等)
+ * 发来的消息。renderer 渲染「由任务「X」发送」标签,点击跳到来源任务。
+ */
+export interface MessageSessionOrigin {
+ kind: 'session';
+ /**
+ * 来源任务 id。共享任务访客收到的来源已由主机脱敏、不带 id(见 main
+ * device-link/sharedTaskMessageOrigin),此时标签只显示通用文案且不可点击。
+ */
+ senderSessionId?: string;
+ /** 发送时的来源任务标题快照;实时标题拿不到时回退用。 */
+ senderSessionTitle?: string;
+ /** 来源任务属于某个伙伴时:标签显示伙伴名与头像(名字优先取实时资料,其次用快照)。 */
+ senderBotId?: string;
+ senderBotName?: string;
+}
+
+/** 非用户手动输入、需要在气泡上标出来源的消息。 */
+export type MessageAutomationOrigin = MessageSchedulerOrigin | MessageSessionOrigin;
+
+/**
+ * agentMeta.origin 的持久化形态(host 写入,见 shared/agentInputQueue 的 origin)。
+ * orca 条目的卡片标题来自 content JSON;这里只关心能否定位发送方任务。
+ */
+export type StoredMessageOrigin =
+ | MessageSchedulerOrigin
+ | (MessageSessionOrigin & { displayText?: string })
+ | { kind: 'orca'; senderLabel?: string; displayText?: string; senderSessionId?: string };
+
/**
* Claude Code SDK 元信息——按消息类型不同填不同子集。
*
@@ -97,9 +127,9 @@ export interface CcMeta {
/**
* Host-side origin marker(与 delivery 同类,非 SDK 字段)。
- * scheduler 注入的 user 消息携带;用户手动输入的消息无此字段。
+ * scheduler / 工具 / Orca 注入的 user 消息携带;用户手动输入的消息无此字段。
*/
- origin?: MessageAutomationOrigin;
+ origin?: StoredMessageOrigin;
/**
* Host-side silent-stop 自动续跑标记(与 delivery 同类,非 SDK 字段)。
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 7737f12908..31bcec8918 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -79,6 +79,7 @@ import { normalizeAutoTitle } from '@cindy/maker-shared/session-title';
import { parseToolLoopErrorDetails } from '@cindy/maker-shared/tool-loop-error';
import type { ToolLoopErrorDetails } from '@cindy/maker-core';
import type { AgentMeta, MessageRole, Message, MessageAutomationOrigin } from '@/lib/ccAgent.types';
+import { toMessageAutomationOrigin } from '@/lib/messageAutomationOrigin';
import {
extractExt,
getMimeType,
@@ -462,8 +463,8 @@ export interface ChatMessage {
*/
ghostReplyPending?: boolean;
/**
- * scheduler 注入的 user 消息来源标记(读自 agentMeta.origin),UserMessage
- * 据此在气泡上方渲染"由自动化任务发送"标签。手动输入的消息无此字段。
+ * scheduler / 其他任务注入的 user 消息来源标记(读自 agentMeta.origin),UserMessage
+ * 据此在气泡上方渲染可点击的来源标签。手动输入的消息无此字段。
*/
automationOrigin?: MessageAutomationOrigin;
sharedAuthorName?: string;
@@ -18241,9 +18242,9 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
};
}
const parsed = parseUserContent(m.content);
- // scheduler 注入的消息带 agentMeta.origin(历史加载与 messages:created
- // 直推两条路径都经过这里),透传给 UserMessage 渲染来源标签。
- const origin = m.agentMeta?.origin;
+ // scheduler / 工具 / Orca 注入的消息带 agentMeta.origin(历史加载与
+ // messages:created 直推两条路径都经过这里),投影后透传给 UserMessage 渲染来源标签。
+ const automationOrigin = toMessageAutomationOrigin(m.agentMeta?.origin);
const delivery = m.agentMeta?.delivery;
const goalObjective = m.agentMeta?.goalObjective;
// Both ingress paths share the Desktop card, but local IM must not opt
@@ -18270,7 +18271,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
...(parsed.sessionReferences && parsed.sessionReferences.length > 0
? { sessionReferences: parsed.sessionReferences }
: {}),
- ...(origin?.kind === 'scheduler' && { automationOrigin: origin }),
+ ...(automationOrigin && { automationOrigin }),
...(delivery === 'turn' || delivery === 'steer' ? { delivery } : {}),
...(goalObjective ? { goalBadge: goalObjective } : {}),
...(hookSource ? { hookSource } : {}),
diff --git a/apps/desktop/src/renderer/lib/messageAutomationOrigin.ts b/apps/desktop/src/renderer/lib/messageAutomationOrigin.ts
new file mode 100644
index 0000000000..e7df1e98b9
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/messageAutomationOrigin.ts
@@ -0,0 +1,34 @@
+import type { MessageAutomationOrigin, StoredMessageOrigin } from '@/lib/ccAgent.types';
+
+/**
+ * 把落库的 agentMeta.origin 投影成气泡来源标签。
+ *
+ * - scheduler:自动化发送,点击跳自动化页;
+ * - session:另一个任务经工具发送,点击跳来源任务;来源任务属于伙伴时带伙伴身份;
+ * - orca:Lead / Worker 互发,卡片本身已标明角色,这里只补可跳转的发送方任务。
+ * 老数据没有 senderSessionId 时不出标签,保持原卡片展示。
+ */
+export function toMessageAutomationOrigin(origin: unknown): MessageAutomationOrigin | undefined {
+ if (!origin || typeof origin !== 'object') return undefined;
+ const value = origin as Partial<StoredMessageOrigin> & Record<string, unknown>;
+ if (value.kind === 'scheduler') return value as MessageAutomationOrigin;
+ if (value.kind !== 'session' && value.kind !== 'orca') return undefined;
+ const senderSessionId = readNonEmptyString(value.senderSessionId);
+ if (value.kind === 'orca')
+ return senderSessionId ? { kind: 'session', senderSessionId } : undefined;
+ // 共享任务访客收到的是主机脱敏后的来源:仍标出「由其他任务发送」,但不带身份、不可跳转。
+ if (!senderSessionId) return { kind: 'session' };
+ const senderSessionTitle = readNonEmptyString(value.senderSessionTitle);
+ const senderBotId = readNonEmptyString(value.senderBotId);
+ const senderBotName = readNonEmptyString(value.senderBotName);
+ return {
+ kind: 'session',
+ senderSessionId,
+ ...(senderSessionTitle ? { senderSessionTitle } : {}),
+ ...(senderBotId ? { senderBotId, ...(senderBotName ? { senderBotName } : {}) } : {}),
+ };
+}
+
+function readNonEmptyString(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
+}
diff --git a/apps/desktop/src/renderer/lib/sessionsStore.ts b/apps/desktop/src/renderer/lib/sessionsStore.ts
index dda1c923dc..7da4f1316f 100644
--- a/apps/desktop/src/renderer/lib/sessionsStore.ts
+++ b/apps/desktop/src/renderer/lib/sessionsStore.ts
@@ -67,7 +67,26 @@ const DEFAULT_LIMIT = 1000;
const startupPerfLog = createLogger('perf/startup');
const initialFetchLogged = new Set<ListStatusFilter>();
-const cache = new Map<ListStatusFilter, Session[]>();
+/** sessionId → 标题的跨桶索引;任何桶写入都会失效,首次读取时惰性重建。 */
+let titleIndex: Map<string, string> | null = null;
+
+/** 桶缓存:每次写入顺带失效标题索引(不依赖各写入点是否随后 notify)。 */
+class SessionBucketCache extends Map<ListStatusFilter, Session[]> {
+ override set(filter: ListStatusFilter, sessions: Session[]): this {
+ titleIndex = null;
+ return super.set(filter, sessions);
+ }
+ override delete(filter: ListStatusFilter): boolean {
+ titleIndex = null;
+ return super.delete(filter);
+ }
+ override clear(): void {
+ titleIndex = null;
+ super.clear();
+ }
+}
+
+const cache = new SessionBucketCache();
const inflight = new Map<ListStatusFilter, Promise<Session[]>>();
/** 列表请求期间收到的 session 费用权威值及其本地事件版本。 */
interface SessionSpendOverride {
@@ -640,6 +659,23 @@ export const sessionsStore = {
* 要先确认标题仍是系统占位,别把用户手动改的名在 UI 上顶掉)。不触发拉取——
* 拿不到就不做乐观更新,交给权威广播回填。
*/
+ /**
+ * 跨桶按 id 取当前标题(O(1),索引随每次桶写入失效后惰性重建)。
+ * 给消息来源标签这类「每条消息都订阅」的消费者用,避免每次变更都各自线性扫描。
+ */
+ getTitleById(id: string): string | null {
+ if (!id) return null;
+ if (!titleIndex) {
+ titleIndex = new Map();
+ for (const bucket of cache.values()) {
+ for (const session of bucket) {
+ if (session.title && !titleIndex.has(session.id)) titleIndex.set(session.id, session.title);
+ }
+ }
+ }
+ return titleIndex.get(id)?.trim() || null;
+ },
+
findById(id: string): Session | null {
if (!id) return null;
for (const bucket of cache.values()) {
diff --git a/apps/desktop/src/shared/__tests__/automaticInputOrigin.test.ts b/apps/desktop/src/shared/__tests__/automaticInputOrigin.test.ts
new file mode 100644
index 0000000000..d22faab857
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/automaticInputOrigin.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+
+import { isAutomaticInputOriginKind } from '../agentInputQueue';
+
+describe('isAutomaticInputOriginKind', () => {
+ it('treats scheduler, goal, Orca and tool-sent session inputs as automatic', () => {
+ for (const kind of ['scheduler', 'goal', 'orca', 'session']) {
+ expect(isAutomaticInputOriginKind(kind)).toBe(true);
+ }
+ });
+
+ it('treats composer input and unknown kinds as human intervention', () => {
+ for (const kind of [undefined, null, 'desktop', 'user', 42]) {
+ expect(isAutomaticInputOriginKind(kind)).toBe(false);
+ }
+ });
+});
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index 08adb3d5da..3ac1e259b7 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -265,6 +265,8 @@ export interface AgentInputQueuedMessage {
kind: 'orca';
senderLabel: string;
displayText?: string;
+ /** 发出本条的 Lead / Worker 会话;接收方据此渲染可点击的来源标签。老快照没有。 */
+ senderSessionId?: string;
}
| {
/**
@@ -280,11 +282,22 @@ export interface AgentInputQueuedMessage {
runId?: string;
}
| {
- /** cindy_helper 的 send_to_session 入队来源;只用于本人排队消息控制授权。 */
+ /**
+ * 另一个会话经工具(send_to_session / steer_session / 伙伴委派等)发来的消息。
+ * 既用于本人排队消息控制授权,也落库到 agentMeta.origin 供接收方渲染来源标签。
+ */
kind: 'session';
senderSessionId: string;
/** 原始可编辑正文;单独保留以兼容未来可能加入的派发包装。 */
displayText: string;
+ /**
+ * 发送时来源会话的标题快照;接收方渲染「由任务「X」发送」标签。来源会话
+ * 之后改名 / 删除时 renderer 优先用实时标题,拿不到再回退这里。老快照没有。
+ */
+ senderSessionTitle?: string;
+ /** 来源会话属于某个伙伴时的伙伴身份快照;接收方标签改显示伙伴名与头像。 */
+ senderBotId?: string;
+ senderBotName?: string;
};
/**
* 本条由**手机控制端**入队 / 插入。
@@ -356,6 +369,15 @@ export type AgentInputRecovery =
| { kind: 'active-turn'; item: AgentInputQueuedMessage }
| null;
+/**
+ * 非真人输入的来源:自动化调度、目标守护、Orca 协同、其他任务经工具投递。
+ * 它们推进同一会话,但不代表用户本人介入——不能给中断续跑的 episode 额度充值。
+ * 队列条目(`origin.kind`)与落库行(`agentMeta.origin.kind`)共用这一个判据。
+ */
+export function isAutomaticInputOriginKind(kind: unknown): boolean {
+ return kind === 'scheduler' || kind === 'goal' || kind === 'orca' || kind === 'session';
+}
+
/**
* Normalize the persisted/device-link clear token used by optimistic input
* preconditions. `null` is a known "never cleared" boundary; `undefined`
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 41b01cd72f..a7b0954430 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -8566,6 +8566,15 @@ export default function SessionScreen() {
router,
]);
+ // 「由任务「X」发送」来源标签:工具只在同一设备的任务之间投递,来源任务与当前任务同设备。
+ const openOriginSession = useCallback((originSessionId: string) => {
+ if (!deviceId || !originSessionId || originSessionId === sessionId) return;
+ router.push({
+ pathname: '/sessions/[sessionId]',
+ params: { sessionId: originSessionId, deviceId, deviceName },
+ });
+ }, [deviceId, deviceName, router, sessionId]);
+
// 正文里会话深链 chip(xdt-maker://session/<id>[?message=<clientId>])点击:
// 同会话带锚点 → setParams 原地定位(不 push 同页新栈帧);跨会话 → 反查所属
// 设备后 push,锚点透传给目标屏的 focusClientId 流程。
@@ -9240,6 +9249,7 @@ export default function SessionScreen() {
onLoadEarlier={loadEarlierMessages}
onLoadToolInput={loadToolInput}
onOpenForkOrigin={forkOrigin ? openForkOrigin : undefined}
+ onOpenOriginSession={openOriginSession}
onBlockingOverlayChange={handleMessageBlockingOverlayChange}
onOpenSessionLink={openSessionLink}
onPreviewRewind={collaborationReadOnlyReason || isSharedTaskPeer(deviceId) ? undefined : previewRewindAtMessage}
diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.ts
index dfddaacbf7..f7a2412c2c 100644
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@ -1132,6 +1132,65 @@ describe('normalizeRemoteMessages', () => {
]);
});
+ it('reads the sending session of tool-sent and Orca messages without mixing it into automation', () => {
+ const items = normalizeRemoteMessages([
+ message({
+ id: 'tool-sent',
+ role: 'user',
+ content: 'please review',
+ agentMeta: {
+ origin: {
+ kind: 'session',
+ senderSessionId: 'caller',
+ displayText: 'please review',
+ senderSessionTitle: 'Release checklist',
+ },
+ },
+ }),
+ message({
+ id: 'orca-report',
+ role: 'user',
+ content: JSON.stringify({ orcaSource: 'worker', content: 'Done' }),
+ agentMeta: { origin: { kind: 'orca', senderLabel: 'Reviewer', senderSessionId: 'worker-1' } },
+ }),
+ message({
+ id: 'teammate-sent',
+ role: 'user',
+ content: 'please sort feedback',
+ agentMeta: {
+ origin: {
+ kind: 'session',
+ senderSessionId: 'bot-task',
+ displayText: 'please sort feedback',
+ senderSessionTitle: 'Weekly feedback',
+ senderBotId: 'bot-1',
+ senderBotName: 'Cindy',
+ },
+ },
+ }),
+ message({
+ id: 'shared-guest',
+ role: 'user',
+ content: 'redacted by host',
+ agentMeta: { origin: { kind: 'session' } },
+ }),
+ message({
+ id: 'legacy-orca',
+ role: 'user',
+ content: 'legacy',
+ agentMeta: { origin: { kind: 'orca', senderLabel: 'Lead' } },
+ }),
+ ]);
+
+ expect(items.map((item) => [item.source.id, item.sessionOrigin, item.automationOrigin])).toEqual([
+ ['tool-sent', { senderSessionId: 'caller', senderSessionTitle: 'Release checklist' }, undefined],
+ ['orca-report', { senderSessionId: 'worker-1' }, undefined],
+ ['teammate-sent', { senderSessionId: 'bot-task', senderSessionTitle: 'Weekly feedback', senderBotName: 'Cindy' }, undefined],
+ ['shared-guest', {}, undefined],
+ ['legacy-orca', undefined, undefined],
+ ]);
+ });
+
it.each(['telegram', 'slack', 'feishu', 'lark', 'discord', 'wechat', 'wecom', 'dingtalk'])(
'ignores additive local %s context metadata and retains ordinary user presentation',
(im) => {
diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.ts
index af02c451b9..869e8c1e4e 100644
--- a/apps/mobile/src/__tests__/pendingSendItems.test.ts
+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts
@@ -476,3 +476,23 @@ describe('pendingSendSpins', () => {
expect(pendingSendSpins('failed')).toBe(false);
});
});
+
+describe('pending bubbles for inputs sent by another task', () => {
+ it('show the persisted visible body, not the agent-facing teammate prefix', () => {
+ const interjection = {
+ ...queued('interject', '[来自 Cindy 的补充]\n\nplease review'),
+ persistedContent: 'please review',
+ origin: { kind: 'session', senderSessionId: 'bot-task', displayText: '[来自 Cindy 的补充]\n\nplease review' },
+ } as QueuedRemoteMessage;
+ const [queuedBubble] = build({ queue: [interjection] });
+ const [settlingBubble] = build({ settling: [interjection] });
+ expect(queuedBubble.text).toBe('please review');
+ expect(settlingBubble.text).toBe('please review');
+ expect(JSON.stringify(queuedBubble.sentInlineTokens)).not.toContain('来自 Cindy');
+ });
+
+ it('keeps ordinary composer items on their own text', () => {
+ const [bubble] = build({ queue: [queued('plain', 'hello')] });
+ expect(bubble.text).toBe('hello');
+ });
+});
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index d540eba438..93845c78db 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -32,6 +32,10 @@
"expand": "Expand",
"automationOriginNamed": "Sent by automation task “{{name}}”",
"automationOrigin": "Sent by an automation task",
+ "sessionOriginNamed": "Sent by session “{{name}}”",
+ "botOriginNamed": "Sent by teammate “{{name}}”",
+ "sessionOrigin": "Sent by another session",
+ "openSessionOrigin": "Opens the source session",
"modelMismatch": "This turn was answered by {{actual}} instead of the selected {{selected}} (temporary server-side downgrade)",
"copyStateCopying": "Copying",
"copyStateCopied": "Copied",
@@ -249,6 +253,7 @@
},
"row": {
"syntheticEditDisabled": "System instruction messages can't be edited or sent as interjections.",
+ "autoSentEditDisabled": "Automatically sent messages can't be edited or sent as interjections.",
"first": "This is already the first item in the queue.",
"last": "This is already the last item in the queue.",
"steering": "Sending interjection",
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 54217dcbe0..c2a5b24528 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -32,6 +32,10 @@
"expand": "展開",
"automationOriginNamed": "自動化タスク「{{name}}」から送信",
"automationOrigin": "自動化タスクから送信",
+ "sessionOriginNamed": "セッション「{{name}}」から送信",
+ "botOriginNamed": "仲間「{{name}}」から送信",
+ "sessionOrigin": "別のセッションから送信",
+ "openSessionOrigin": "送信元のセッションを開きます",
"modelMismatch": "今回は選択した {{selected}} ではなく {{actual}} が応答しました(サーバー側の一時的なダウングレード)",
"copyStateCopying": "コピー中",
"copyStateCopied": "コピーしました",
@@ -249,6 +253,7 @@
},
"row": {
"syntheticEditDisabled": "システム指令メッセージは編集や割り込み送信ができません。",
+ "autoSentEditDisabled": "自動送信されたメッセージは編集や割り込み送信ができません。",
"first": "すでにキューの先頭です。",
"last": "すでにキューの末尾です。",
"steering": "割り込み送信中",
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index 91b7cd350b..254fd4cef5 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -32,6 +32,10 @@
"expand": "펼치기",
"automationOriginNamed": "자동화 작업 「{{name}}」에서 전송",
"automationOrigin": "자동화 작업에서 전송",
+ "sessionOriginNamed": "세션 “{{name}}”에서 보냄",
+ "botOriginNamed": "동료 “{{name}}”에서 보냄",
+ "sessionOrigin": "다른 세션에서 보냄",
+ "openSessionOrigin": "보낸 세션을 엽니다",
"modelMismatch": "이번 턴은 선택한 {{selected}}이(가) 아니라 {{actual}}이(가) 응답했습니다(서버 측 임시 다운그레이드)",
"copyStateCopying": "복사 중",
"copyStateCopied": "복사됨",
@@ -249,6 +253,7 @@
},
"row": {
"syntheticEditDisabled": "시스템 지시 메시지는 편집하거나 끼어들기로 보낼 수 없습니다.",
+ "autoSentEditDisabled": "자동으로 보낸 메시지는 편집하거나 끼어들기로 보낼 수 없습니다.",
"first": "이미 큐의 첫 항목입니다.",
"last": "이미 큐의 마지막 항목입니다.",
"steering": "끼어들기 전송 중",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index dd483675ef..a0c44eb5d1 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -32,6 +32,10 @@
"expand": "展开",
"automationOriginNamed": "由自动化「{{name}}」发送",
"automationOrigin": "由自动化发送",
+ "sessionOriginNamed": "由任务「{{name}}」发送",
+ "botOriginNamed": "由伙伴「{{name}}」发送",
+ "sessionOrigin": "由其他任务发送",
+ "openSessionOrigin": "打开来源任务",
"modelMismatch": "本轮由 {{actual}} 响应,而非所选的 {{selected}}(服务端临时降级)",
"copyStateCopying": "复制中",
"copyStateCopied": "已复制",
@@ -249,6 +253,7 @@
},
"row": {
"syntheticEditDisabled": "系统指令消息不支持编辑或插话发送。",
+ "autoSentEditDisabled": "自动发送的消息不支持编辑或插话发送。",
"first": "已经是队列第一条。",
"last": "已经是队列最后一条。",
"steering": "插话发送中",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index dac9dea733..f1f6f852b8 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -32,6 +32,10 @@
"expand": "展開",
"automationOriginNamed": "由自動化「{{name}}」傳送",
"automationOrigin": "由自動化傳送",
+ "sessionOriginNamed": "由任務「{{name}}」傳送",
+ "botOriginNamed": "由夥伴「{{name}}」傳送",
+ "sessionOrigin": "由其他任務傳送",
+ "openSessionOrigin": "開啟來源任務",
"modelMismatch": "本輪由 {{actual}} 響應,而非所選的 {{selected}}(服務端臨時降級)",
"copyStateCopying": "複製中",
"copyStateCopied": "已複製",
@@ -249,6 +253,7 @@
},
"row": {
"syntheticEditDisabled": "系統指令訊息不支援編輯或插話傳送。",
+ "autoSentEditDisabled": "自動傳送的訊息不支援編輯或插話傳送。",
"first": "已經是佇列第一條。",
"last": "已經是佇列最後一條。",
"steering": "插話傳送中",
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 6d8d2161ab..85b5471c6c 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -648,6 +648,8 @@ interface MessageActions {
onDeleteMessage?: (clientId: string) => void;
onLoadEarlier?: () => void | Promise<void>;
onOpenForkOrigin?: () => void;
+ /** 「由任务「X」发送」来源标签点击:跳到同一设备上的来源任务。 */
+ onOpenOriginSession?: (sessionId: string) => void;
onOpenPayload?: (payload: MessagePayload) => void;
onLoadToolInput?: (ref: MobileToolInputProjection) => Promise<MobileToolInputDetail>;
onBlockingOverlayChange?: (blocked: boolean) => void;
@@ -701,6 +703,7 @@ export function MessageRenderer({
onLoadEarlier,
onLoadToolInput,
onOpenForkOrigin,
+ onOpenOriginSession,
onBlockingOverlayChange,
onOpenSessionLink,
onPreviewRewind,
@@ -1664,6 +1667,7 @@ export function MessageRenderer({
onForkMessage,
onDeleteMessage,
onOpenForkOrigin,
+ onOpenOriginSession,
onOpenSessionLink,
onPreviewRewind,
onEnterShareSelection,
@@ -1708,6 +1712,7 @@ export function MessageRenderer({
onDeleteMessage,
onForkMessage,
onOpenForkOrigin,
+ onOpenOriginSession,
onLoadToolInput,
onOpenSessionLink,
onPreviewRewind,
@@ -2881,8 +2886,15 @@ const RenderItemView = memo(function RenderItemView({
? <CompanionMessageCard message={item.message}
renderMarkdown={(text) => <CompanionCardMarkdown text={text} actions={actions} />} />
: item.message.orcaCard
- ? <OrcaCollabCard card={item.message.orcaCard} screenWidth={actions.screenWidth}
- blockKey={JSON.stringify([actions.remoteDeviceId, item.key])} />
+ ? (
+ <>
+ {item.message.sessionOrigin ? (
+ <SessionOriginLabel origin={item.message.sessionOrigin} onOpen={actions.onOpenOriginSession} />
+ ) : null}
+ <OrcaCollabCard card={item.message.orcaCard} screenWidth={actions.screenWidth}
+ blockKey={JSON.stringify([actions.remoteDeviceId, item.key])} />
+ </>
+ )
: <MessageBubble item={hookSourceUserItem ?? systemCardUserItem ?? item} actions={actions} />;
break;
case 'thinking':
@@ -3005,6 +3017,41 @@ const RenderListItemView = memo(function RenderListItemView({
);
});
+/** 另一个任务经工具发来的消息:气泡上方的来源标签,点按跳来源任务(对齐桌面 AutomationOriginBadge)。 */
+function SessionOriginLabel({
+ origin,
+ onOpen,
+}: {
+ origin: NonNullable<NormalizedRemoteMessage['sessionOrigin']>;
+ onOpen?: (sessionId: string) => void;
+}) {
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ const senderSessionId = origin.senderSessionId;
+ const openTarget = onOpen && senderSessionId ? () => onOpen(senderSessionId) : undefined;
+ const label = origin.senderBotName
+ ? t('message.renderer.botOriginNamed', { name: origin.senderBotName })
+ : origin.senderSessionTitle
+ ? t('message.renderer.sessionOriginNamed', { name: origin.senderSessionTitle })
+ : t('message.renderer.sessionOrigin');
+ return (
+ <Pressable
+ accessibilityHint={openTarget ? t('message.renderer.openSessionOrigin') : undefined}
+ accessibilityLabel={label}
+ accessibilityRole={openTarget ? 'button' : 'text'}
+ disabled={!openTarget}
+ hitSlop={8}
+ onPress={openTarget}
+ style={styles.automationOriginRow}
+ testID="message.sessionOrigin"
+ >
+ <Send color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.thin} />
+ <Text numberOfLines={1} style={styles.automationOriginText}>{label}</Text>
+ </Pressable>
+ );
+}
+
function ForkOriginMarker({ onOpenForkOrigin }: { onOpenForkOrigin?: () => void }) {
const { colors } = useTheme();
const { t } = useTranslation();
@@ -3686,6 +3733,9 @@ function MessageBubble({
</Text>
</View>
) : null}
+ {item.message.kind === 'user' && item.message.sessionOrigin ? (
+ <SessionOriginLabel origin={item.message.sessionOrigin} onOpen={actions.onOpenOriginSession} />
+ ) : null}
{attachmentStripNode}
{hasBubbleContent || (!attachmentStripNode && messageQuotes.length === 0) ? bubble : null}
{item.message.rawError ? <AgentErrorDetails key={item.message.key} message={item.message.rawError} /> : null}
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index f286217ce7..51418e8b7e 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -130,6 +130,12 @@ export interface NormalizedRemoteMessage {
isTurnFinalAssistant?: boolean;
/** user 专用:scheduler 注入的消息来源(agentMeta.origin);驱动更紧的收起阈值与来源标签。 */
automationOrigin?: NormalizedAutomationOrigin;
+ /**
+ * user 专用:另一个任务经工具(send_to_session / 伙伴委派 / Orca 协同等)发来的消息来源
+ * (agentMeta.origin kind=session,或带 senderSessionId 的 orca);渲染可点击的来源标签。
+ * 不进分享投影:来源任务标题属于用户本机上下文,不随分享图外发。
+ */
+ sessionOrigin?: NormalizedSessionOrigin;
/** 共享 Cindy relay 派发的来源;用于移动端还原 Slack / Telegram 任务卡。 */
hookSource?: NormalizedHookSource;
/**
@@ -142,6 +148,15 @@ export interface NormalizedRemoteMessage {
isSyntheticTrigger?: boolean;
}
+/** 另一个任务经工具发来的消息来源(对齐桌面 MessageSessionOrigin)。 */
+export interface NormalizedSessionOrigin {
+ /** 共享任务访客收到的来源已由主机脱敏、不带 id:只显示通用文案,不可点按。 */
+ senderSessionId?: string;
+ senderSessionTitle?: string;
+ /** 来源任务属于伙伴时的伙伴名快照;有则标签显示伙伴名。 */
+ senderBotName?: string;
+}
+
/** scheduler 注入消息的来源标记(对齐桌面 MessageAutomationOrigin)。 */
export interface NormalizedAutomationOrigin {
scheduleId: string;
@@ -429,6 +444,7 @@ export function normalizeRemoteMessages(
orcaCard: reportCard,
align: 'agent',
createdAt: message.createdAt,
+ ...readSessionOrigin(message),
});
continue;
}
@@ -509,6 +525,7 @@ export function normalizeRemoteMessages(
...turnCost,
...readModelMismatch(message),
...(message.role === 'user' ? readAutomationOrigin(message) : {}),
+ ...(message.role === 'user' ? readSessionOrigin(message) : {}),
...(hookSource ? { hookSource } : {}),
});
}
@@ -994,6 +1011,26 @@ function readModelMismatch(message: RemoteMessage): Pick<NormalizedRemoteMessage
return { modelMismatch: { selected, actual } };
}
+// 工具投递落库时在 agentMeta.origin 写 { kind:'session', senderSessionId, senderSessionTitle? };
+// Orca 互发写 { kind:'orca', senderSessionId? }(老数据没有 senderSessionId,不出标签)。
+function readSessionOrigin(message: RemoteMessage): Pick<NormalizedRemoteMessage, 'sessionOrigin'> {
+ const origin = readRecord(message.agentMeta?.origin);
+ if (!origin || (origin.kind !== 'session' && origin.kind !== 'orca')) return {};
+ const senderSessionId = readString(origin.senderSessionId)?.trim();
+ if (!senderSessionId) return origin.kind === 'session' ? { sessionOrigin: {} } : {};
+ const senderSessionTitle = origin.kind === 'session' ? readString(origin.senderSessionTitle)?.trim() : undefined;
+ const senderBotName = origin.kind === 'session' && readString(origin.senderBotId)
+ ? (readString(origin.senderBotName)?.trim() || readString(origin.senderBotId)?.trim())
+ : undefined;
+ return {
+ sessionOrigin: {
+ senderSessionId,
+ ...(senderSessionTitle ? { senderSessionTitle } : {}),
+ ...(senderBotName ? { senderBotName } : {}),
+ },
+ };
+}
+
// scheduler runner 落库时在 agentMeta.origin 写 { kind:'scheduler', scheduleId, scheduleName? }
// (见桌面 MessageAutomationOrigin);其它 kind 或缺 scheduleId 的一律忽略。
function readAutomationOrigin(message: RemoteMessage): Pick<NormalizedRemoteMessage, 'automationOrigin'> {
diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.ts
index 1fa32db457..3eac758043 100644
--- a/apps/mobile/src/session/pendingSendItems.ts
+++ b/apps/mobile/src/session/pendingSendItems.ts
@@ -15,6 +15,7 @@
* 未派发条目保持队列 / outbox 顺序。已派发气泡在分组前占据本地用户消息的位置,
* 正式回流以同一个 clientId 原位替换,不比较控制端与主机的时钟。
*/
+import { queueItemVisibleText } from '@cindy/maker-shared/queue';
import { syntheticTriggerKind } from '@cindy/maker-shared/synthetic-trigger';
import {
parseChatQuoteSegments,
@@ -136,13 +137,17 @@ export function mergePendingSendItems(
/**
* 气泡显示文本:合成 UI 指令行(桌面「失败后继续」等隐藏 prompt)用遮蔽标签替代原文
* —— 裸英文指令不能给用户看(对齐桌面 PendingQueuePanel 的 i18n 遮蔽标签)。
+ * 自动化 / 其他任务发来的条目显示落库可见正文(不带发给 Agent 的前缀或协议),
+ * 与回流后的正式消息一致(queueItemVisibleText,与桌面排队面板同判据)。
*/
export function pendingSendBubbleText(
- item: Pick<QueuedRemoteMessage, 'text' | 'chatMessage'>,
+ item: Pick<QueuedRemoteMessage, 'text' | 'chatMessage'>
+ & Partial<Pick<QueuedRemoteMessage, 'persistedContent' | 'files' | 'origin'>>,
): string {
+ const agentText = queueItemVisibleText(item);
const visibleText = item.chatMessage.quotesEncoded === true
- ? stripChatQuoteMarkerLines(item.text)
- : item.text;
+ ? stripChatQuoteMarkerLines(agentText)
+ : agentText;
const kind = syntheticTriggerKind(visibleText);
if (kind === 'continue') return i18n.t('message.queue.continueSystemInstruction');
if (kind === 'generic') return i18n.t('message.queue.systemInstruction');
@@ -257,7 +262,7 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobile
clientId: item.clientId,
text: pendingSendBubbleText(item),
sentInlineTokens: buildPendingSentInlineTokens({
- text: item.text,
+ text: queueItemVisibleText(item),
quotesEncoded: item.chatMessage.quotesEncoded,
pastedTextRanges: item.chatMessage.pastedTextRanges,
slashCommandRanges: item.chatMessage.slashCommandRanges,
diff --git a/packages/maker-shared/src/__tests__/queue.test.ts b/packages/maker-shared/src/__tests__/queue.test.ts
index 6f84a47d9e..ffd9ae5928 100644
--- a/packages/maker-shared/src/__tests__/queue.test.ts
+++ b/packages/maker-shared/src/__tests__/queue.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, it } from 'vitest';
import {
buildQueuePanelSummary,
buildQueueRowPresentation,
+ isAutoSentQueueItem,
isOrcaQueueItem,
+ queueItemVisibleText,
queueMoveTargetIndex,
stopOptionsForProjection,
} from '../queue.js';
@@ -282,4 +284,58 @@ describe('shared queue presentation model', () => {
expect(normalRow.syntheticKind).toBeNull();
expect(normalRow.actions.edit.disabled).toBe(false);
});
+
+ it('locks edit and steer (but keeps remove and reorder) for auto-sent rows', () => {
+ const projection = {
+ steeringQueueClientIds: [],
+ queueEditLocks: [],
+ queueInteractionLocks: [],
+ };
+ for (const origin of [
+ { kind: 'session', senderSessionId: 'caller', displayText: 'follow-up' },
+ { kind: 'scheduler', scheduleId: 's', scheduleName: 'nightly' },
+ ]) {
+ const item = { ...queued('q-1'), text: 'follow-up', origin };
+ expect(isAutoSentQueueItem(item)).toBe(true);
+ const row = buildQueueRowPresentation({ item, originalIndex: 0, projection, queueLength: 2 });
+ expect(row.actions.edit.disabled).toBe(true);
+ expect(row.actions.steer.disabled).toBe(true);
+ expect(row.actions.edit.disabledReason).toBe('自动发送的消息不支持编辑或插话发送。');
+ expect(row.actions.remove.disabled).toBe(false);
+ expect(row.actions.moveDown.disabled).toBe(false);
+ }
+ expect(isAutoSentQueueItem({ origin: { kind: 'orca', senderLabel: 'Lead' } })).toBe(false);
+ expect(isAutoSentQueueItem({})).toBe(false);
+ });
+});
+
+describe('queueItemVisibleText', () => {
+ it('shows the persisted body for session and scheduler items', () => {
+ expect(queueItemVisibleText({
+ text: '[来自 Cindy 的补充]\n\nplease review',
+ persistedContent: 'please review',
+ origin: { kind: 'session', senderSessionId: 'bot-task' },
+ })).toBe('please review');
+ expect(queueItemVisibleText({
+ text: 'heartbeat prompt\n[silent-run protocol]',
+ persistedContent: 'heartbeat prompt',
+ origin: { kind: 'scheduler', scheduleId: 's' },
+ })).toBe('heartbeat prompt');
+ });
+
+ it('unwraps the host attachment envelope only when files are attached', () => {
+ const origin = { kind: 'session', senderSessionId: 'caller' };
+ expect(queueItemVisibleText({
+ text: 'see attached',
+ persistedContent: JSON.stringify({ text: 'see attached', images: [], files: [{ name: 'a.txt' }] }),
+ files: [{ name: 'a.txt' }],
+ origin,
+ })).toBe('see attached');
+ expect(queueItemVisibleText({ text: '{"text":"x"}', persistedContent: '{"text":"x"}', origin })).toBe('{"text":"x"}');
+ });
+
+ it('keeps the agent text for composer and Orca items', () => {
+ expect(queueItemVisibleText({ text: 'hello', persistedContent: 'other' })).toBe('hello');
+ expect(queueItemVisibleText({ text: 'wire', persistedContent: '{}', origin: { kind: 'orca', senderLabel: 'Lead' } })).toBe('wire');
+ });
});
diff --git a/packages/maker-shared/src/queue.ts b/packages/maker-shared/src/queue.ts
index 146511e816..6fffe12f74 100644
--- a/packages/maker-shared/src/queue.ts
+++ b/packages/maker-shared/src/queue.ts
@@ -139,7 +139,11 @@ export function buildQueueRowPresentation(input: {
// 照常——用户可以取消一条排队中的续跑,但不能改写或抢发它的内容。
const syntheticEditReason = syntheticKind
? presentationText(localizer, 'message.queuePresentation.row.syntheticEditDisabled', '系统指令消息不支持编辑或插话发送。')
- : null;
+ : isAutoSentQueueItem(input.item)
+ // 自动化 / 其他任务经工具排进来的消息(对齐桌面 canEdit / canSteer=false):改写后
+ // 落库气泡的来源标签就不再属实;删除与排序照常。
+ ? presentationText(localizer, 'message.queuePresentation.row.autoSentEditDisabled', '自动发送的消息不支持编辑或插话发送。')
+ : null;
return {
actions: {
@@ -188,6 +192,41 @@ export function isOrcaQueueItem(
return origin?.kind === 'orca';
}
+/** 自动化(scheduler)或其他任务经工具(session)排进来的消息。Orca 另有整行只读口径。 */
+export function isAutoSentQueueItem(
+ item: Pick<{ origin?: unknown }, 'origin'>,
+): boolean {
+ const kind = readRecord(item.origin)?.kind;
+ return kind === 'scheduler' || kind === 'session';
+}
+
+/**
+ * 排队条目给人看的正文。自动化调度或其他任务经工具发来(origin.kind 为 scheduler /
+ * session)的条目,`text` 是发给 Agent 的原文——可能带「[来自 X 的补充]」前缀或静默运行
+ * 协议——可见正文以落库的 `persistedContent` 为准;带附件时落库是主机构造的
+ * `{text, images, files}` 信封,取其中 text(只在确有附件时解包,正文本身是 JSON 的消息
+ * 原样显示)。其它条目沿用 `text`。桌面排队面板、手机待发送气泡与共享访客投影共用此判据。
+ */
+export function queueItemVisibleText(item: {
+ text?: string;
+ persistedContent?: string;
+ files?: readonly unknown[];
+ origin?: unknown;
+}): string {
+ const text = item.text ?? '';
+ if (!isAutoSentQueueItem(item)) return text;
+ const persisted = item.persistedContent || text;
+ if (!item.files?.length) return persisted;
+ try {
+ const envelope = JSON.parse(persisted) as unknown;
+ const envelopeText = readRecord(envelope)?.text;
+ if (typeof envelopeText === 'string') return envelopeText;
+ } catch {
+ // Not an envelope: the persisted row is already the visible text.
+ }
+ return persisted;
+}
+
function readRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>