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。

fix(desktop): address queue edit review feedback

DavidShena6f36163ec5d
diff --git a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
index ef5a259743..cb6ac03f6a 100644
--- a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
@@ -62,6 +62,17 @@ describe('rewriteOutboundMedia — channel gating', () => {
expect(parseAttachmentOssRef(rewritten.files[1].path)?.ossKey).toBe('cindy/device-link/shared-task/sharedTask/u/new.png');
expect(rewritten.persistedContent).not.toContain('/controller/new.png');
});
+ it('rewrites newly added ordinary device-link queue-edit attachments', async () => {
+ uploadLocalFile.mockResolvedValue({ key: 'cindy/device-link/u/new.png', contentType: 'image/png', size: 10, sha256: SHA256 });
+ const item = { files: [{ path: '/target/cache/old.png' }, { path: '/controller/new.png' }], persistedContent: JSON.stringify({ files: [{ path: '/target/cache/old.png' }, { path: '/controller/new.png' }] }) };
+ const result = await rewriteOutboundMedia('maker:input:update-content', ['task', 'client', item], new Set(['/target/cache/old.png']));
+ expect(uploadLocalFile).toHaveBeenCalledTimes(1);
+ expect(uploadLocalFile).toHaveBeenCalledWith('/controller/new.png', {});
+ const rewritten = result[2] as typeof item;
+ expect(rewritten.files[0].path).toBe('/target/cache/old.png');
+ expect(parseAttachmentOssRef(rewritten.files[1].path)?.ossKey).toBe('cindy/device-link/u/new.png');
+ expect(rewritten.persistedContent).not.toContain('/controller/new.png');
+ });
it('非媒体 channel → 原样,不上传', async () => {
const args = [{ a: 1 }];
const out = await rewriteOutboundMedia('maker:set-model', args);
diff --git a/apps/desktop/src/main/device-link/__tests__/sessionReferenceCompatibility.test.ts b/apps/desktop/src/main/device-link/__tests__/sessionReferenceCompatibility.test.ts
index af9004cf6b..856a5b3690 100644
--- a/apps/desktop/src/main/device-link/__tests__/sessionReferenceCompatibility.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/sessionReferenceCompatibility.test.ts
@@ -6,11 +6,13 @@ import { handleInvoke, type DeviceLinkIpcDeps } from '../ipc.js';
function depsForInvoke(
invoke: DeviceLinkIpcDeps['invoke'],
rewrite = vi.fn(async (_channel: string, args: unknown[]) => args),
+ rewriteMedia?: DeviceLinkIpcDeps['rewriteOutboundMedia'],
): DeviceLinkIpcDeps {
return {
getState: () => ({ disabledControlDeviceIds: [] }) as never,
invoke,
rewriteOutboundSessionReferences: rewrite,
+ ...(rewriteMedia ? { rewriteOutboundMedia: rewriteMedia } : {}),
} as unknown as DeviceLinkIpcDeps;
}
@@ -173,4 +175,61 @@ describe('device-link target session-reference capability gate', () => {
]),
).rejects.toThrow('[SESSION_REFERENCE_UNAVAILABLE]');
});
+
+ it('rewrites ordinary queue-edit attachments using the target projection', async () => {
+ const invoke = vi
+ .fn<DeviceLinkIpcDeps['invoke']>()
+ .mockResolvedValueOnce({
+ ok: true,
+ result: {
+ sessionId: 'target-session',
+ pendingQueue: [{ clientId: 'client-1', files: [{ path: '/target/old.png' }] }],
+ },
+ })
+ .mockResolvedValueOnce({ ok: true, result: { accepted: true } });
+ const rewriteMedia = vi.fn(async (
+ _channel: string,
+ args: unknown[],
+ existing?: ReadonlySet<string>,
+ ) => {
+ expect(existing).toEqual(new Set(['/target/old.png']));
+ return args;
+ });
+
+ await expect(
+ handleInvoke(depsForInvoke(invoke, undefined, rewriteMedia), 'target-device', 'maker:input:update-content', [
+ 'target-session',
+ 'client-1',
+ { files: [{ path: '/target/old.png' }, { path: '/controller/new.png' }] },
+ ]),
+ ).resolves.toEqual({ accepted: true });
+
+ expect(invoke).toHaveBeenNthCalledWith(1, 'target-device', 'maker:input:get-projection', ['target-session']);
+ expect(invoke).toHaveBeenNthCalledWith(2, 'target-device', 'maker:input:update-content', [
+ 'target-session',
+ 'client-1',
+ { files: [{ path: '/target/old.png' }, { path: '/controller/new.png' }] },
+ ]);
+ expect(rewriteMedia).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the update-content channel error visible for an old target', async () => {
+ const invoke = vi
+ .fn<DeviceLinkIpcDeps['invoke']>()
+ .mockResolvedValueOnce({
+ ok: false,
+ error: { code: 'CHANNEL_NOT_ALLOWED', message: 'projection unavailable' },
+ });
+ const rewriteMedia = vi.fn(async (_channel: string, args: unknown[]) => args);
+
+ await expect(
+ handleInvoke(depsForInvoke(invoke, undefined, rewriteMedia), 'target-device', 'maker:input:update-content', [
+ 'target-session',
+ 'client-1',
+ { files: [{ path: '/controller/new.png' }] },
+ ]),
+ ).rejects.toThrow('[DEVICE_LINK_CHANNEL_NOT_ALLOWED]');
+ expect(rewriteMedia).not.toHaveBeenCalled();
+ expect(invoke).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.ts
index 23bcf9884c..37e1888507 100644
--- a/apps/desktop/src/main/device-link/ipc.ts
+++ b/apps/desktop/src/main/device-link/ipc.ts
@@ -663,15 +663,24 @@ export async function handleInvoke(
try {
const peer = parseSharedTaskPeer(normalizedDeviceId);
let existing: ReadonlySet<string> | undefined;
- if (peer?.role === 'host' && channel === 'maker:input:update-content') {
+ let projectionUnavailable = false;
+ if ((!peer || peer.role === 'host') && channel === 'maker:input:update-content') {
const projection = await deps.invoke(normalizedDeviceId, 'maker:input:get-projection', [callArgs[0]]);
- if (!projection.ok) throw new Error(projection.error.message);
- const value = projection.result as { sessionId?: string; pendingQueue?: Array<{ clientId: string; files?: Array<{ path?: string; url?: string }> }> };
- if (value?.sessionId !== callArgs[0] || !Array.isArray(value.pendingQueue)) throw new Error('Invalid shared input projection');
- const item = value.pendingQueue.find((row) => row.clientId === callArgs[1]);
- if (!item) throw new Error('Queued message is no longer pending');
- existing = new Set((item.files ?? []).flatMap((file) => [file.path, file.url].filter((ref): ref is string => typeof ref === 'string')));
- assertControlTargetEnabled(deps, normalizedDeviceId);
+ if (projection.ok) {
+ const value = projection.result as { sessionId?: string; pendingQueue?: Array<{ clientId: string; files?: Array<{ path?: string; url?: string }> }> };
+ if (value?.sessionId !== callArgs[0] || !Array.isArray(value.pendingQueue)) throw new Error('Invalid input projection');
+ const item = value.pendingQueue.find((row) => row.clientId === callArgs[1]);
+ if (!item) throw new Error('Queued message is no longer pending');
+ existing = new Set((item.files ?? []).flatMap((file) => [file.path, file.url].filter((ref): ref is string => typeof ref === 'string')));
+ assertControlTargetEnabled(deps, normalizedDeviceId);
+ } else if (projection.error.code !== 'CHANNEL_NOT_ALLOWED') {
+ throw new Error(projection.error.message);
+ } else {
+ projectionUnavailable = true;
+ }
+ }
+ if (projectionUnavailable) {
+ throwIpcError('DEVICE_LINK_CHANNEL_NOT_ALLOWED', 'Queued content editing is not supported by the target device');
}
callArgs = await withSharedTaskMedia(peer?.role === 'host' ? peer.sharedTaskId : undefined,
() => existing ? deps.rewriteOutboundMedia!(channel, callArgs, existing) : deps.rewriteOutboundMedia!(channel, callArgs));
diff --git a/apps/desktop/src/main/device-link/outboundMedia.ts b/apps/desktop/src/main/device-link/outboundMedia.ts
index e78a374425..9362570d05 100644
--- a/apps/desktop/src/main/device-link/outboundMedia.ts
+++ b/apps/desktop/src/main/device-link/outboundMedia.ts
@@ -3,7 +3,7 @@
* 把 block 的 path/url 替换成 OSS 引用串(随 invoke 走 relay,bytes 不内联)。
* ---------------------------------------------------------------------------
* 在 device-link handleInvoke 里、deps.invoke 之前对 maker:send / maker:steer /
- * maker:input:enqueue 调用(这些 channel 才携带用户消息附件)。失败抛错 → handleInvoke
+ * maker:input:enqueue / maker:input:update-content 调用(这些 channel 才携带用户消息附件)。失败抛错 → handleInvoke
* 转 throwIpcError(DEVICE_LINK_MEDIA_TRANSFER_FAILED) → 整条消息不发(产品决策)。
*
* 被控端 normalizeUserMessage 识别 OSS 引用串 → presign-get 下载 → 物化喂 agent。
@@ -365,9 +365,10 @@ async function rewriteQueued(item: unknown, existing: ReadonlySet<string> = new
* 抛错由 handleInvoke 转 MEDIA_TRANSFER_FAILED。
*/
export async function rewriteOutboundMedia(channel: string, args: unknown[], existing: ReadonlySet<string> = new Set()): Promise<unknown[]> {
- if (channel === 'maker:input:update-content' && sharedTaskMediaId()) {
+ if (channel === 'maker:input:update-content') {
const next = [...args];
next[2] = await rewriteQueued(next[2], existing);
+ log.debug(`outbound media rewritten for ${channel}`);
return next;
}
const isQueued = QUEUED_SHAPE_CHANNELS.has(channel);
diff --git a/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts b/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts
index 4a46afba2f..93385682c6 100644
--- a/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts
+++ b/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts
@@ -435,6 +435,84 @@ describe('renderer input queue facade', () => {
);
});
+ it('falls back to update-text when an old device-link target lacks update-content', async () => {
+ const sid = `legacy-content-${Math.random().toString(36).slice(2, 8)}`;
+ const item = queued('q-legacy-content', 'old text');
+ makerChatStore.initGlobalListeners();
+ projectionHandler?.(projection(sid, { pendingQueue: [item] }));
+ input.updateContent.mockRejectedValueOnce(
+ new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] update-content unavailable'),
+ );
+ input.updateText.mockImplementationOnce(async (sessionId: string) =>
+ projection(sessionId, {
+ pendingQueue: [{
+ ...item,
+ text: 'edited text',
+ persistedContent: item.persistedContent,
+ chatMessage: { ...item.chatMessage, content: 'edited text' },
+ }],
+ }),
+ );
+
+ const saved = await makerChatStore.updateQueueItemContent(sid, item.clientId, {
+ content: {
+ text: 'edited text',
+ mentions: [],
+ hasQuotes: false,
+ agentReferences: [],
+ pastedTextRanges: [],
+ slashCommandRanges: [],
+ },
+ files: [],
+ });
+
+ expect(saved).toBe(true);
+ expect(input.updateText).toHaveBeenCalledWith(sid, item.clientId, 'edited text', undefined);
+ });
+
+ it('does not fall back to update-text when queue edit attachments change', async () => {
+ const sid = `legacy-attachment-${Math.random().toString(36).slice(2, 8)}`;
+ const item = queued('q-legacy-attachment', 'keep text');
+ item.files = [{
+ id: 'old-file',
+ name: 'old.png',
+ path: 'C:\\images\\old.png',
+ ext: 'png',
+ size: 1,
+ category: 'image',
+ mimeType: 'image/png',
+ }];
+ makerChatStore.initGlobalListeners();
+ projectionHandler?.(projection(sid, { pendingQueue: [item] }));
+ input.updateContent.mockRejectedValueOnce(
+ new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] update-content unavailable'),
+ );
+ input.updateText.mockClear();
+
+ await expect(
+ makerChatStore.updateQueueItemContent(sid, item.clientId, {
+ content: {
+ text: 'edited text',
+ mentions: [],
+ hasQuotes: false,
+ agentReferences: [],
+ pastedTextRanges: [],
+ slashCommandRanges: [],
+ },
+ files: [{
+ id: 'new-file',
+ name: 'new.png',
+ path: 'C:\\images\\new.png',
+ ext: 'png',
+ size: 1,
+ category: 'image',
+ mimeType: 'image/png',
+ }],
+ }),
+ ).rejects.toThrow('update-content unavailable');
+ expect(input.updateText).not.toHaveBeenCalled();
+ });
+
it('supports attachment-only queue edits and rejects a fully empty replacement', async () => {
const sid = `attachment-only-${Math.random().toString(36).slice(2, 8)}`;
const item = queued('q-attachment-only', '');
diff --git a/apps/desktop/src/renderer/lib/__tests__/queueComposerEdit.test.ts b/apps/desktop/src/renderer/lib/__tests__/queueComposerEdit.test.ts
index 7cb0b4cd67..ca1ef37ce9 100644
--- a/apps/desktop/src/renderer/lib/__tests__/queueComposerEdit.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/queueComposerEdit.test.ts
@@ -70,4 +70,66 @@ describe('queueMessageToComposerEditDraft', () => {
expect(prepared.draft.text).toBeNull();
expect(prepared.draft.attachments).toHaveLength(1);
});
+
+ it('restores structured references, file mentions and pasted text chips', () => {
+ const entry = queuedMessage();
+ const messageHref = 'cindy://session/source?message=message-1';
+ const projectHref = 'cindy://project/C%3A%2Fworkspace';
+ const text =
+ `See ${messageHref} and [Workspace](${projectHref}) with @src/app.ts and pasted selection`;
+ const messageStart = text.indexOf(messageHref);
+ const projectText = `[Workspace](${projectHref})`;
+ const projectStart = text.indexOf(projectText);
+ const pastedText = 'pasted selection';
+ const pastedStart = text.indexOf(pastedText);
+ entry.text = text;
+ entry.chatMessage.content = text;
+ entry.mentions = [{ type: 'file', name: 'app.ts', path: 'src/app.ts' }];
+ entry.chatMessage.agentReferences = [
+ {
+ kind: 'message',
+ start: messageStart,
+ end: messageStart + messageHref.length,
+ href: messageHref,
+ sessionId: 'source',
+ messageClientId: 'message-1',
+ text: 'Referenced message',
+ },
+ {
+ kind: 'project',
+ start: projectStart,
+ end: projectStart + projectText.length,
+ href: projectHref,
+ name: 'Workspace',
+ workingDir: 'C:\\workspace',
+ },
+ ];
+ entry.chatMessage.pastedTextRanges = [
+ { start: pastedStart, end: pastedStart + pastedText.length, display: 'selection' },
+ ];
+
+ const prepared = queueMessageToComposerEditDraft('session-1', entry);
+ const inline = prepared.draft.text?.content?.[0]?.content ?? [];
+
+ expect(inline).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: 'mentionChip',
+ attrs: expect.objectContaining({ kind: 'session', path: messageHref }),
+ }),
+ expect.objectContaining({
+ type: 'mentionChip',
+ attrs: expect.objectContaining({ kind: 'project', path: projectHref, label: 'Workspace', titled: true }),
+ }),
+ expect.objectContaining({
+ type: 'mentionChip',
+ attrs: expect.objectContaining({ kind: 'file', path: 'src/app.ts', label: 'app.ts' }),
+ }),
+ expect.objectContaining({
+ type: 'pastedTextChip',
+ attrs: expect.objectContaining({ text: pastedText, display: 'selection' }),
+ }),
+ ]),
+ );
+ });
});
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index ae5135d21f..d0da651908 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -13682,6 +13682,50 @@ function cleanupUnacceptedQueueEditMaterialization(
});
}
+function queueEditFilesMatch(
+ left: readonly AttachedFile[] | undefined,
+ right: readonly AttachedFile[] | undefined,
+): boolean {
+ const stable = (files: readonly AttachedFile[] | undefined) =>
+ (files ?? []).map((file) => ({
+ id: file.id,
+ name: file.name,
+ path: file.path,
+ ext: file.ext,
+ size: file.size,
+ category: file.category,
+ mimeType: file.mimeType,
+ url: file.url,
+ originalName: file.originalName ?? file.name,
+ base64: file.base64,
+ textContent: file.textContent,
+ truncated: file.truncated,
+ annotated: file.annotated,
+ annotationSourceUrl: file.annotationSourceUrl,
+ annotationStrokes: file.annotationStrokes,
+ }));
+ return JSON.stringify(stable(left)) === JSON.stringify(stable(right));
+}
+
+function canFallbackQueueEditToText(
+ queued: QueuedMessage,
+ replacement: QueuedMessage,
+ content: QueueItemContentUpdate['content'],
+ files: readonly AttachedFile[],
+): boolean {
+ if (!content.text.trim() || !queueEditFilesMatch(queued.files, files)) return false;
+ if (JSON.stringify(queued.mentions ?? []) !== JSON.stringify(content.mentions ?? [])) return false;
+ if ((queued.chatMessage.quotesEncoded === true) !== content.hasQuotes) return false;
+ if ((queued.chatMessage.agentReferences?.length ?? 0) > 0) return false;
+ if ((queued.agentReferences?.length ?? 0) > 0) return false;
+ if ((queued.chatMessage.pastedTextRanges?.length ?? 0) > 0) return false;
+ if ((queued.chatMessage.slashCommandRanges?.length ?? 0) > 0) return false;
+ if (replacement.chatMessage.agentReferences?.length) return false;
+ if (replacement.chatMessage.pastedTextRanges?.length) return false;
+ if (replacement.chatMessage.slashCommandRanges?.length) return false;
+ return true;
+}
+
async function updateQueueItemContent(
sessionId: string,
clientId: string,
@@ -13753,8 +13797,31 @@ async function updateQueueItemContent(
: input.updateContent(sessionId, clientId, replacement),
));
} catch (error) {
- cleanupUnacceptedQueueEditMaterialization(files, preparedFiles);
- throw error;
+ if (
+ extractIpcError(error)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED' &&
+ canFallbackQueueEditToText(queued, replacement, content, preparedFiles)
+ ) {
+ try {
+ ({ projection } = await runInputProjectionOperation(sessionId, (input) =>
+ boundaryOpts
+ ? input.updateText(
+ sessionId,
+ clientId,
+ content.text,
+ replacement.sessionRefs,
+ undefined,
+ boundaryOpts,
+ )
+ : input.updateText(sessionId, clientId, content.text, replacement.sessionRefs),
+ ));
+ } catch (fallbackError) {
+ cleanupUnacceptedQueueEditMaterialization(files, preparedFiles);
+ throw fallbackError;
+ }
+ } else {
+ cleanupUnacceptedQueueEditMaterialization(files, preparedFiles);
+ throw error;
+ }
}
const accepted = projection.pendingQueue.find((item) => item.clientId === clientId);
const updated = queuedContentProjectionMatches(accepted, replacement);
diff --git a/apps/desktop/src/renderer/lib/queueComposerEdit.ts b/apps/desktop/src/renderer/lib/queueComposerEdit.ts
index fce0305dc2..9e7b3c741b 100644
--- a/apps/desktop/src/renderer/lib/queueComposerEdit.ts
+++ b/apps/desktop/src/renderer/lib/queueComposerEdit.ts
@@ -1,9 +1,14 @@
+import { readAgentInputReferences } from '@cindy/maker-shared/agent-input-projection';
+import type { JSONContent } from '@tiptap/core';
+
import type { ComposerDraft } from '@/lib/composerDraftStore';
-import { plainTextToTiptapDoc } from '@/lib/composerDraftStore';
-import { parseChatQuoteSegments } from '@/lib/chatQuotes';
-import { quoteSegmentsToComposerDocument } from '@/lib/composerQuoteDocument';
+import { formatQuoteForSend, parseChatQuoteSegments, type ChatQuoteSegment } from '@/lib/chatQuotes';
+import { COMPOSER_QUOTE_NODE_TYPE } from '@/lib/composerQuoteDocument';
+import { normalizeComposerDocumentJSON } from '@/lib/composerListDocument';
import type { AttachedFile } from '@/lib/fileTypes';
import type { QueuedMessage } from '@/lib/makerChatStore';
+import { formatMentionRef } from '@/lib/mentionRefFormat';
+import type { AgentInputMention, AgentInputReference } from '../../shared/agentInputQueue';
export interface QueueComposerEditDraft {
draftKey: string;
@@ -15,6 +20,274 @@ export function queueComposerEditDraftKey(sessionId: string, clientId: string):
return `queue-edit:${sessionId}:${clientId}`;
}
+interface InlineReplacement {
+ start: number;
+ end: number;
+ node: JSONContent;
+ priority: number;
+}
+
+function oneLine(value: string): string {
+ return value.replace(/\s+/g, ' ').trim();
+}
+
+function agentReferenceNode(reference: AgentInputReference, sourceText: string): JSONContent {
+ const titled = sourceText.startsWith('[');
+ if (reference.kind === 'message') {
+ return {
+ type: 'mentionChip',
+ attrs: {
+ kind: 'session',
+ label: oneLine(reference.text ?? '') || reference.messageClientId,
+ path: reference.href,
+ titled: false,
+ ...(reference.text ? { agentText: reference.text } : {}),
+ ...(reference.truncated ? { agentTextTruncated: true } : {}),
+ },
+ };
+ }
+ if (reference.kind === 'session') {
+ return {
+ type: 'mentionChip',
+ attrs: {
+ kind: 'session',
+ label: oneLine(reference.title ?? '') || reference.sessionId,
+ path: reference.href,
+ titled,
+ },
+ };
+ }
+ if (reference.kind === 'project') {
+ return {
+ type: 'mentionChip',
+ attrs: {
+ kind: 'project',
+ label: oneLine(reference.name) || reference.workingDir,
+ path: reference.href,
+ titled,
+ },
+ };
+ }
+ if (reference.kind === 'browser-tab') {
+ return {
+ type: 'mentionChip',
+ attrs: {
+ kind: 'browser-tab',
+ label: oneLine(reference.title ?? '') || reference.url,
+ path: reference.href,
+ },
+ };
+ }
+ if (reference.kind === 'desktop-window') {
+ return {
+ type: 'mentionChip',
+ attrs: {
+ kind: 'desktop-window',
+ label: oneLine(reference.title ?? '') || oneLine(reference.appName),
+ path: reference.href,
+ },
+ };
+ }
+ if (reference.kind === 'plugin-resource') {
+ return {
+ type: 'mentionChip',
+ attrs: {
+ kind: 'plugin-resource',
+ label: reference.label,
+ path: reference.href,
+ sourceLabel: reference.pluginName,
+ ...(reference.description ? { sourceDescription: reference.description } : {}),
+ },
+ };
+ }
+ return {
+ type: 'mentionChip',
+ attrs: { kind: 'bot', label: reference.name, path: reference.botId },
+ };
+}
+
+function mentionWireText(mention: AgentInputMention): string {
+ if (mention.type === 'dir') return `@${formatMentionRef(`${mention.path}/`)}`;
+ if (mention.type === 'agent') {
+ const path = mention.path.includes('/')
+ ? mention.path
+ : mention.path.replace(/\.md$/, '');
+ return `@${formatMentionRef(path)}`;
+ }
+ return `@${formatMentionRef(mention.path)}`;
+}
+
+function collectInlineReplacements(entry: QueuedMessage, text: string): InlineReplacement[] {
+ const replacements: InlineReplacement[] = [];
+ const agentReferences = readAgentInputReferences(
+ entry.chatMessage.agentReferences?.length
+ ? entry.chatMessage.agentReferences
+ : entry.agentReferences,
+ text,
+ );
+ for (const reference of agentReferences) {
+ replacements.push({
+ start: reference.start,
+ end: reference.end,
+ node: agentReferenceNode(reference, text.slice(reference.start, reference.end)),
+ priority: 0,
+ });
+ }
+
+ for (const range of entry.chatMessage.pastedTextRanges ?? []) {
+ if (
+ !Number.isSafeInteger(range.start) ||
+ !Number.isSafeInteger(range.end) ||
+ range.start < 0 ||
+ range.end <= range.start ||
+ range.end > text.length ||
+ typeof range.display !== 'string'
+ ) {
+ continue;
+ }
+ replacements.push({
+ start: range.start,
+ end: range.end,
+ node: {
+ type: 'pastedTextChip',
+ attrs: { text: text.slice(range.start, range.end), display: range.display },
+ },
+ priority: 1,
+ });
+ }
+
+ const mentionsByWireText = new Map<string, AgentInputMention>();
+ for (const mention of entry.mentions ?? []) mentionsByWireText.set(mentionWireText(mention), mention);
+ for (const [wireText, mention] of mentionsByWireText) {
+ let start = text.indexOf(wireText);
+ while (start >= 0) {
+ replacements.push({
+ start,
+ end: start + wireText.length,
+ node: {
+ type: 'mentionChip',
+ attrs: { kind: mention.type, label: mention.name, path: mention.path, titled: false },
+ },
+ priority: 2,
+ });
+ start = text.indexOf(wireText, start + wireText.length);
+ }
+ }
+
+ replacements.sort((left, right) =>
+ left.start - right.start || left.priority - right.priority || left.end - right.end,
+ );
+ const accepted: InlineReplacement[] = [];
+ let previousEnd = 0;
+ for (const replacement of replacements) {
+ if (replacement.start < previousEnd) continue;
+ accepted.push(replacement);
+ previousEnd = replacement.end;
+ }
+ return accepted;
+}
+
+function locateTextSegmentStarts(
+ text: string,
+ segments: readonly ChatQuoteSegment[],
+): Array<number | null> {
+ let cursor = 0;
+ return segments.map((segment) => {
+ const value = segment.kind === 'quote' ? formatQuoteForSend(segment.quote) : segment.text;
+ const start = text.indexOf(value, cursor);
+ if (start < 0) return null;
+ cursor = start + value.length;
+ return segment.kind === 'text' ? start : null;
+ });
+}
+
+function textSegmentNodes(
+ text: string,
+ sourceStart: number | null,
+ replacements: readonly InlineReplacement[],
+): JSONContent[] {
+ if (sourceStart === null) return text ? [{ type: 'text', text }] : [];
+ const sourceEnd = sourceStart + text.length;
+ const nodes: JSONContent[] = [];
+ let cursor = sourceStart;
+ for (const replacement of replacements) {
+ if (replacement.start < sourceStart || replacement.end > sourceEnd) continue;
+ if (replacement.start > cursor) {
+ nodes.push({ type: 'text', text: text.slice(cursor - sourceStart, replacement.start - sourceStart) });
+ }
+ nodes.push(replacement.node);
+ cursor = replacement.end;
+ }
+ if (cursor < sourceEnd) nodes.push({ type: 'text', text: text.slice(cursor - sourceStart) });
+ return nodes;
+}
+
+const LIST_ROW_MARKER_RE = /^(?:[-+*•][ \t]+|[1-9]\d{0,8}[.)][ \t]+|[1-9]\d{0,8}、[ \t]*)/;
+
+function structuredQueueDocument(entry: QueuedMessage, text: string): JSONContent | null {
+ if (!text) return null;
+ const segments = entry.chatMessage.quotesEncoded
+ ? parseChatQuoteSegments(text)
+ : [{ kind: 'text' as const, text }];
+ const segmentStarts = locateTextSegmentStarts(text, segments);
+ const replacements = collectInlineReplacements(entry, text);
+ const content: JSONContent[] = [];
+ let inlineContent: JSONContent[] = [];
+ let quoteJustEnded = false;
+
+ const finishParagraph = () => {
+ content.push(
+ inlineContent.length > 0
+ ? { type: 'paragraph', content: inlineContent }
+ : { type: 'paragraph' },
+ );
+ inlineContent = [];
+ };
+
+ segments.forEach((segment, index) => {
+ if (segment.kind === 'quote') {
+ inlineContent.push({
+ type: COMPOSER_QUOTE_NODE_TYPE,
+ attrs: {
+ text: segment.quote.text,
+ sourcePath: segment.quote.sourcePath ?? null,
+ startLine: segment.quote.startLine ?? null,
+ endLine: segment.quote.endLine ?? null,
+ },
+ });
+ quoteJustEnded = true;
+ return;
+ }
+ if (!segment.text) return;
+ if (/^\n+$/.test(segment.text)) {
+ inlineContent.push(
+ ...Array.from({ length: segment.text.length }, () => ({ type: 'hardBreak' })),
+ );
+ return;
+ }
+
+ for (const node of textSegmentNodes(segment.text, segmentStarts[index], replacements)) {
+ if (node.type !== 'text') {
+ inlineContent.push(node);
+ quoteJustEnded = false;
+ continue;
+ }
+ const lines = (node.text ?? '').split('\n');
+ lines.forEach((line, lineIndex) => {
+ if (quoteJustEnded && line && LIST_ROW_MARKER_RE.test(line) && inlineContent.length > 0) {
+ finishParagraph();
+ }
+ if (line) inlineContent.push({ ...node, text: line });
+ if (lineIndex < lines.length - 1) finishParagraph();
+ if (line) quoteJustEnded = false;
+ });
+ }
+ });
+
+ finishParagraph();
+ return normalizeComposerDocumentJSON({ type: 'doc', content });
+}
+
export function queueMessageToComposerEditDraft(
sessionId: string,
entry: QueuedMessage,
@@ -25,11 +298,7 @@ export function queueMessageToComposerEditDraft(
cacheUrlShared: true,
stagedPathShared: true,
}));
- const document = entry.chatMessage.quotesEncoded
- ? quoteSegmentsToComposerDocument(parseChatQuoteSegments(text))
- : text.length > 0
- ? plainTextToTiptapDoc(text)
- : null;
+ const document = structuredQueueDocument(entry, text);
return {
draftKey: queueComposerEditDraftKey(sessionId, entry.clientId),