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。

Migrated from makecindy/cindy-temp#502 (#232)

Lizie69e0cac7594
diff --git a/apps/desktop/src/main/__tests__/agentInputQueue.test.ts b/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
index 8a6a3ec964..4f96fe0596 100644
--- a/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
+++ b/apps/desktop/src/main/__tests__/agentInputQueue.test.ts
@@ -4,8 +4,10 @@ import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';
import {
ANNOTATED_IMAGE_NOTE,
buildMakerUserMessage,
+ getAgentFacingText,
reconcileSessionRefsForText,
sanitizeQueuedMessageForPersistence,
+ updateQueuedMessageContent,
updateQueuedMessageText,
} from '../../shared/agentInputQueue.js';
@@ -274,6 +276,38 @@ describe('agentInputQueue', () => {
expect(entry.trustedSessionReferenceContexts).toHaveLength(1);
});
+ it('strips hydrated message-chip bodies from both queue reference copies', () => {
+ const entry = queuedMessage(undefined);
+ const href = 'cindy://session/source?message=message-1';
+ const reference = {
+ kind: 'message' as const,
+ start: 0,
+ end: href.length,
+ href,
+ sessionId: 'source',
+ messageClientId: 'message-1',
+ text: 'process-local referenced body',
+ truncated: true,
+ };
+ entry.text = href;
+ entry.agentReferences = [reference];
+ entry.persistedContent = JSON.stringify({
+ text: href,
+ agentReferences: [reference],
+ });
+
+ const persisted = sanitizeQueuedMessageForPersistence(entry);
+
+ expect(persisted.agentReferences?.[0]).not.toHaveProperty('text');
+ expect(persisted.agentReferences?.[0]).not.toHaveProperty('truncated');
+ expect(JSON.parse(persisted.persistedContent).agentReferences[0])
+ .not.toHaveProperty('text');
+ expect(JSON.parse(persisted.persistedContent).agentReferences[0])
+ .not.toHaveProperty('truncated');
+ expect(JSON.stringify(persisted)).not.toContain('process-local referenced body');
+ expect(entry.agentReferences?.[0]).toHaveProperty('text', 'process-local referenced body');
+ });
+
it('reconciles both current and legacy session links on queue edits', () => {
expect(
reconcileSessionRefsForText(
@@ -285,4 +319,96 @@ describe('agentInputQueue', () => {
{ sessionId: 'legacy' },
]);
});
+
+ it('projects encoded quote markers for Agent use without changing queue or persistence wire', () => {
+ const entry = queuedMessage(undefined);
+ const text = '> <!-- cindy-composer-quote -->\n> selected\n\nreply';
+ entry.text = text;
+ entry.persistedContent = JSON.stringify({ text, quotesEncoded: true });
+ entry.chatMessage.content = text;
+ entry.chatMessage.quotesEncoded = true;
+
+ expect(getAgentFacingText(entry)).toBe('> selected\n\nreply');
+ expect(buildMakerUserMessage(entry)).toEqual({
+ type: 'user',
+ content: '> selected\n\nreply',
+ });
+ expect(entry.text).toBe(text);
+ expect(entry.persistedContent).toBe(JSON.stringify({ text, quotesEncoded: true }));
+ expect(entry.chatMessage).toMatchObject({ content: text, quotesEncoded: true });
+ });
+
+ it('keeps a hand-written marker when quotesEncoded is false', () => {
+ const entry = queuedMessage(undefined);
+ entry.text = '> <!-- cindy-composer-quote -->\n> hand written';
+ entry.chatMessage.content = entry.text;
+
+ expect(getAgentFacingText(entry)).toBe(entry.text);
+ });
+
+ it('expands a message chip to its full semantic body instead of sending only the deep link', () => {
+ const entry = queuedMessage(undefined);
+ const href = 'cindy://session/session-a?message=message-a';
+ entry.text = `please inspect ${href}`;
+ entry.chatMessage.content = entry.text;
+ entry.agentReferences = [{
+ kind: 'message',
+ start: entry.text.indexOf(href),
+ end: entry.text.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Complete target message body',
+ }];
+
+ const projected = getAgentFacingText(entry);
+ expect(projected).toContain('Complete target message body');
+ expect(projected).toContain('Session ID: session-a');
+ expect(projected).toContain('Message ID: message-a');
+ expect(projected).not.toContain(href);
+ });
+
+ it('leaves slash, long-paste text and file mentions unchanged for Agent delivery', () => {
+ const entry = queuedMessage(undefined);
+ entry.text = '/learn\nfull pasted body\n@"docs/spec.md"';
+ entry.chatMessage.content = entry.text;
+ entry.chatMessage.pastedTextRanges = [{
+ start: 7,
+ end: 23,
+ display: 'Pasted text (2 lines)',
+ }];
+ entry.chatMessage.slashCommandRanges = [{ start: 0, end: 6 }];
+ entry.mentions = [{ type: 'file', name: 'spec.md', path: 'docs/spec.md' }];
+
+ expect(buildMakerUserMessage(entry)).toEqual({
+ type: 'user',
+ content: [
+ { type: 'text', text: entry.text },
+ { type: 'mention', name: 'spec.md', path: 'docs/spec.md', kind: 'file' },
+ ],
+ });
+ });
+
+ it('replaces or clears structured reference offsets during queue content edits', () => {
+ const old = queuedMessage(undefined);
+ old.agentReferences = [{
+ kind: 'session',
+ start: 0,
+ end: old.text.length,
+ href: 'cindy://session/old',
+ sessionId: 'old',
+ }];
+ const next = queuedMessage(undefined);
+ next.text = 'plain replacement';
+ next.persistedContent = JSON.stringify({
+ text: next.text,
+ images: [],
+ files: [],
+ });
+ next.chatMessage.content = next.text;
+
+ const updated = updateQueuedMessageContent(old, next);
+ expect(updated.agentReferences).toBeUndefined();
+ expect(updated.persistedContent).toBe(next.persistedContent);
+ });
});
diff --git a/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts b/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts
index 377ffcc671..04171a4ced 100644
--- a/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts
@@ -144,4 +144,28 @@ describe('extractText — messages.content JSON → 纯文本', () => {
expect(extractText(undefined, 'assistant')).toBe('');
expect(extractText(JSON.stringify({ noText: 1 }), 'user')).toBe('');
});
+
+ it('标题素材使用 semantic projection,保留 raw wire 但不暴露 quote marker / 私有深链', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const text = `> <!-- cindy-composer-quote -->\n> selected\n\ninspect ${href}`;
+ const raw = JSON.stringify({
+ text,
+ quotesEncoded: true,
+ agentReferences: [{
+ kind: 'message',
+ start: text.indexOf(href),
+ end: text.indexOf(href) + href.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Target message body',
+ }],
+ });
+
+ const projected = extractText(raw, 'user');
+ expect(projected).not.toContain('cindy-composer-quote');
+ expect(projected).not.toContain(href);
+ expect(projected).toContain('Target message body');
+ expect(JSON.parse(raw)).toMatchObject({ text, quotesEncoded: true });
+ });
});
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 7df8c8d446..62b416322f 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
@@ -3488,8 +3488,8 @@ describe('AgentInputCoordinator steer transaction', () => {
const sid = 'steer-ghost-block';
const first = makeItem('q-1', 'first');
const second = makeItem('q-2', 'second');
- h.setScreenUserMessage(async (_sid, queued) =>
- queued.clientId === 'q-2'
+ h.setScreenUserMessage(async (_sid, agentFacingText) =>
+ agentFacingText === 'second'
? { action: 'block', ghostId: 'g-1', ghostName: 'guard', reason: 'nope' }
: { action: 'allow' },
);
@@ -3521,8 +3521,8 @@ describe('AgentInputCoordinator steer transaction', () => {
const sid = 'steer-ghost-rewrite';
const first = makeItem('q-1', 'first');
const second = makeItem('q-2', 'second');
- h.setScreenUserMessage(async (_sid, queued) =>
- queued.clientId === 'q-2'
+ h.setScreenUserMessage(async (_sid, agentFacingText) =>
+ agentFacingText === 'second'
? { action: 'rewrite', ghostId: 'g-1', ghostName: 'guard', text: 'rewritten text' }
: { action: 'allow' },
);
@@ -4857,10 +4857,69 @@ describe('AgentInputCoordinator enqueue clientId 幂等去重(弱网重发防线
});
describe('AgentInputCoordinator 意识拦截钩(订阅槽①,will-user-message)', () => {
+ it('projects quote markers and structured references for Ghost, turn and steer', async () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const raw = `> <!-- cindy-composer-quote -->\n> selected\n\ninspect ${href}`;
+ const item = makeItem('semantic-turn', raw, {
+ persistedContent: JSON.stringify({ text: raw, quotesEncoded: true }),
+ agentReferences: [{
+ kind: 'message',
+ start: raw.indexOf(href),
+ end: raw.indexOf(href) + href.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Target message body',
+ }],
+ chatMessage: {
+ clientId: 'semantic-turn',
+ role: 'user',
+ content: raw,
+ quotesEncoded: true,
+ },
+ });
+
+ const turn = createHarness();
+ const turnScreen = vi.fn<NonNullable<AgentInputCoordinatorDeps['screenUserMessage']>>(
+ async () => ({ action: 'allow' }) as const,
+ );
+ turn.setScreenUserMessage(turnScreen);
+ turn.coordinator.enqueue('semantic-turn-session', item);
+ await flush();
+
+ const turnScreenText = turnScreen.mock.calls[0]?.[1];
+ expect(turnScreenText).not.toContain('cindy-composer-quote');
+ expect(turnScreenText).not.toContain(href);
+ expect(turnScreenText).toContain('Target message body');
+ const turnText = (turn.sendToAgent.mock.calls[0]?.[1] as { content: string }).content;
+ expect(turnText).toBe(turnScreenText);
+
+ const steer = createHarness();
+ steer.setRunning(true);
+ const steerScreen = vi.fn<NonNullable<AgentInputCoordinatorDeps['screenUserMessage']>>(
+ async () => ({ action: 'allow' }) as const,
+ );
+ steer.setScreenUserMessage(steerScreen);
+ const steerItem = {
+ ...item,
+ clientId: 'semantic-steer',
+ chatMessage: { ...item.chatMessage, clientId: 'semantic-steer' },
+ };
+ expect(await steer.coordinator.steer('semantic-steer-session', steerItem)).toBe(true);
+ await flush();
+
+ const steerScreenText = steerScreen.mock.calls[0]?.[1];
+ expect(steerScreenText).not.toContain('cindy-composer-quote');
+ expect(steerScreenText).not.toContain(href);
+ expect(steerScreenText).toContain('Target message body');
+ const steerText = (steer.steerToAgent.mock.calls[0]?.[1] as { content: string }).content;
+ expect(steerText).toBe(steerScreenText);
+ });
+
it('block:丢弃排队项(不落库不派发),回调 onUserMessageBlocked,后续消息继续放行', async () => {
const h = createHarness();
- h.setScreenUserMessage(async (_sid, item) =>
- item.text.includes('敏感')
+ h.setScreenUserMessage(async (_sid, agentFacingText) =>
+ agentFacingText.includes('敏感')
? { action: 'block', ghostId: 'g1', ghostName: '哨兵', reason: '含敏感词' }
: { action: 'allow' },
);
@@ -4989,6 +5048,49 @@ describe('AgentInputCoordinator 意识拦截钩(订阅槽①,will-user-message)'
const rewrittenItem = h.onUserMessageRewritten.mock.calls[0]?.[1];
expect(rewrittenItem?.chatMessage.quotesEncoded).toBeUndefined();
});
+
+ it('rewrite:clears stale Composer reference offsets from wire and Agent input', async () => {
+ const h = createHarness();
+ const href = 'cindy://session/session-a?message=message-a';
+ const original = `inspect ${href}`;
+ h.setScreenUserMessage(async () => ({
+ action: 'rewrite',
+ ghostId: 'g1',
+ ghostName: '哨兵',
+ text: `rewritten ${href}`,
+ }) as const);
+ const reference = {
+ kind: 'message' as const,
+ start: original.indexOf(href),
+ end: original.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Target message body',
+ };
+ h.coordinator.enqueue('s1', makeItem('c1', original, {
+ persistedContent: JSON.stringify({
+ text: original,
+ agentReferences: [reference],
+ }),
+ agentReferences: [reference],
+ }));
+
+ await flush();
+
+ expect(h.sendToAgent.mock.calls[0]?.[1]).toEqual({
+ type: 'user',
+ content: `rewritten ${href}`,
+ });
+ const persisted = mocks.createMessage.mock.calls.find(
+ (call) => (call[1] as { clientId?: string }).clientId === 'c1',
+ )?.[1] as { content: string };
+ expect(JSON.parse(persisted.content)).toEqual({
+ text: `rewritten ${href}`,
+ slashCommandRanges: [],
+ });
+ expect(h.onUserMessageRewritten.mock.calls[0]?.[1].agentReferences).toBeUndefined();
+ });
});
describe('AgentInputCoordinator scheduler 排队心跳(撞忙排队桥)', () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
index 8bcf44cf5f..05637ca0ff 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
@@ -30,6 +30,34 @@ describe('extractPlainText', () => {
expect(extractPlainText(42)).toBe('');
expect(extractPlainText(null)).toBe('');
});
+
+ it('DB user envelope uses semantic projection for quote and message chips', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const text = `> <!-- cindy-composer-quote -->\n> selected\n\ninspect ${href}`;
+ const content = {
+ text,
+ quotesEncoded: true,
+ agentReferences: [{
+ kind: 'message',
+ start: text.indexOf(href),
+ end: text.indexOf(href) + href.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Target message body',
+ }],
+ };
+
+ const projected = extractPlainText(JSON.stringify(content));
+ expect(projected).not.toContain('cindy-composer-quote');
+ expect(projected).not.toContain(href);
+ expect(projected).toContain('Target message body');
+ });
+
+ it('DB user envelope preserves a hand-written marker without quotesEncoded', () => {
+ const text = '> <!-- cindy-composer-quote -->\n> hand written';
+ expect(extractPlainText({ text, quotesEncoded: false })).toBe(text);
+ });
});
describe('buildHandoffText', () => {
@@ -85,6 +113,31 @@ describe('buildHandoffText', () => {
expect(text).toContain('正常消息');
});
+ it('handoff history never exposes product quote markers or private deep-link-only semantics', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const text = `> <!-- cindy-composer-quote -->\n> selected\n\ninspect ${href}`;
+ const handoff = buildHandoffText([
+ msg('user', {
+ text,
+ quotesEncoded: true,
+ agentReferences: [{
+ kind: 'message',
+ start: text.indexOf(href),
+ end: text.indexOf(href) + href.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Target message body',
+ }],
+ }),
+ msg('assistant', 'done'),
+ ], opts);
+
+ expect(handoff).not.toContain('cindy-composer-quote');
+ expect(handoff).not.toContain(href);
+ expect(handoff).toContain('Target message body');
+ });
+
it('超长文本被逐条截断,总长受硬上限保护', () => {
const big = 'x'.repeat(50_000);
const messages: HandoffSourceMessage[] = [];
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentInputReferences.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentInputReferences.test.ts
new file mode 100644
index 0000000000..75d846d6cb
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentInputReferences.test.ts
@@ -0,0 +1,144 @@
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';
+import type { DbClient } from '../../localDb/client/DbClient.js';
+import {
+ clearCurrentDbClient,
+ setCurrentDbClient,
+} from '../../localDb/client/current.js';
+import * as schema from '../../localDb/schema.js';
+import { hydrateQueuedAgentReferences } from '../agentInputReferences.js';
+
+describe('hydrateQueuedAgentReferences message visibility', () => {
+ let rawDb: Database.Database;
+ let client: DbClient;
+
+ beforeEach(() => {
+ rawDb = new Database(':memory:');
+ rawDb.exec(`
+ CREATE TABLE sessions (
+ id TEXT PRIMARY KEY,
+ cleared_at INTEGER
+ );
+ CREATE TABLE messages (
+ id TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ role TEXT NOT NULL,
+ content TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ rewind_at INTEGER
+ );
+ INSERT INTO sessions (id, cleared_at) VALUES ('source-session', NULL);
+ `);
+ client = {
+ query: async <T = unknown>(sql: string, params: unknown[] = []) =>
+ rawDb.prepare(sql).all(...params) as T[],
+ queryOne: async <T = unknown>(sql: string, params: unknown[] = []) =>
+ rawDb.prepare(sql).get(...params) as T | undefined,
+ exec: async (sql, params = []) => rawDb.prepare(sql).run(...params),
+ tx: async () => {
+ throw new Error('tx is not used by this test');
+ },
+ drizzle: drizzle(rawDb, { schema }),
+ vecAvailable: false,
+ dispose: async () => {},
+ };
+ setCurrentDbClient(client, 'test-user');
+ });
+
+ afterEach(() => {
+ clearCurrentDbClient(client);
+ rawDb.close();
+ });
+
+ function seedMessage(rewindAt: number | null): void {
+ rawDb.prepare(`
+ INSERT INTO messages (
+ id, client_id, session_id, role, content, created_at, rewind_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
+ `).run(
+ 'row-1',
+ 'target-message',
+ 'source-session',
+ 'assistant',
+ 'Authoritative visible body',
+ 200,
+ rewindAt,
+ );
+ }
+
+ function queued(capturedText = 'Composer-captured fallback'): AgentInputQueuedMessage {
+ const href = 'cindy://session/source-session?message=target-message';
+ const text = `inspect ${href}`;
+ const reference = {
+ kind: 'message' as const,
+ start: text.indexOf(href),
+ end: text.length,
+ href,
+ sessionId: 'source-session',
+ messageClientId: 'target-message',
+ text: capturedText,
+ };
+ return {
+ clientId: 'queued-message',
+ text,
+ persistedContent: JSON.stringify({ text, agentReferences: [reference] }),
+ agentReferences: [reference],
+ model: 'claude-opus-4-7',
+ effort: 'medium',
+ permissionMode: 'default',
+ workingDir: '/repo',
+ chatMessage: {
+ clientId: 'queued-message',
+ role: 'user',
+ content: text,
+ isStreaming: false,
+ createdAt: '2026-07-23T00:00:00.000Z',
+ },
+ createOpts: {
+ agentKind: 'claude-code',
+ workingDir: '/repo',
+ model: 'claude-opus-4-7',
+ effort: 'medium',
+ permissionMode: 'default',
+ userPrompt: '',
+ makerMemoryEnabled: true,
+ displayReasoning: 'summarized',
+ },
+ };
+ }
+
+ it('hydrates a visible target from the authoritative host DB', async () => {
+ seedMessage(null);
+
+ const hydrated = await hydrateQueuedAgentReferences(queued());
+
+ expect(hydrated.agentReferences?.[0]).toMatchObject({
+ kind: 'message',
+ text: 'Authoritative visible body',
+ });
+ });
+
+ it('does not re-inject a rewound target through captured fallback text', async () => {
+ seedMessage(300);
+
+ const hydrated = await hydrateQueuedAgentReferences(queued());
+
+ expect(hydrated.agentReferences?.[0]).not.toHaveProperty('text');
+ expect(JSON.parse(hydrated.persistedContent).agentReferences[0]).not.toHaveProperty('text');
+ });
+
+ it('does not re-inject a target hidden by the session clear boundary', async () => {
+ seedMessage(null);
+ rawDb.prepare('UPDATE sessions SET cleared_at = ? WHERE id = ?')
+ .run(250, 'source-session');
+
+ const hydrated = await hydrateQueuedAgentReferences(queued());
+
+ expect(hydrated.agentReferences?.[0]).not.toHaveProperty('text');
+ expect(JSON.parse(hydrated.persistedContent).agentReferences[0]).not.toHaveProperty('text');
+ });
+});
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 81a8b4676f..3c8a3099b4 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -39,6 +39,7 @@ import type {
} from '../../shared/agentInputQueue.js';
import {
buildMakerUserMessage,
+ getAgentFacingText,
projectionRetryText,
sanitizeQueuedMessageForPersistence,
updateQueuedMessageContent,
@@ -149,7 +150,7 @@ export interface AgentInputCoordinatorDeps {
*/
screenUserMessage?: (
sessionId: string,
- item: AgentInputQueuedMessage,
+ agentFacingText: string,
) => Promise<
| { action: 'allow' }
| { action: 'block'; ghostId: string; ghostName: string; reason: string }
@@ -1014,7 +1015,7 @@ export class AgentInputCoordinator {
// marker 已置位,筛查期间并发 steer / drain 被挡;stop / clearSession 竞态
// 由筛查后的 marker 复查兜底。
if (!item.bypassGhostHooks && this.deps.screenUserMessage) {
- const verdict = await this.deps.screenUserMessage(sessionId, item);
+ const verdict = await this.deps.screenUserMessage(sessionId, getAgentFacingText(item));
const cur = this.getState(sessionId);
if (!cur.steeringQueueClientIds.includes(item.clientId)) {
// stop/close/clearSession 赢在筛查期间:steer 事务已被取消,静默放弃。
@@ -1039,7 +1040,8 @@ export class AgentInputCoordinator {
return true;
}
if (verdict.action === 'rewrite') {
- // 与 drain 的 rewrite 同构:JSON-aware 只换 text 字段,附件/引用信封保留。
+ // 与 drain 的 rewrite 同构:JSON-aware 只换 text 字段并保留附件信封;
+ // 整体改写后旧 Composer reference offsets 已失效,必须同步清掉。
const originalText = item.text;
const rewritten = updateQueuedMessageText(item, verdict.text);
Object.assign(item, rewritten);
@@ -1048,6 +1050,7 @@ export class AgentInputCoordinator {
if (!rewritten.sessionReferencesRequireTrustedSnapshot) {
delete item.sessionReferencesRequireTrustedSnapshot;
}
+ delete item.agentReferences;
this.deps.onUserMessageRewritten?.(sessionId, item, {
ghostId: verdict.ghostId,
ghostName: verdict.ghostName,
@@ -1952,7 +1955,7 @@ export class AgentInputCoordinator {
// 留痕署名后照常派发。activeTurn 已置位,并发 drain 被挡住,询问期间
// 不会抢发下一条。
if (!head.bypassGhostHooks && this.deps.screenUserMessage) {
- const verdict = await this.deps.screenUserMessage(sessionId, head);
+ const verdict = await this.deps.screenUserMessage(sessionId, getAgentFacingText(head));
if (!this.isActiveTurnCurrent(sessionId, active)) return;
if (verdict.action === 'block') {
this.getState(sessionId).activeTurn = null;
@@ -1977,6 +1980,7 @@ export class AgentInputCoordinator {
if (!rewritten.sessionReferencesRequireTrustedSnapshot) {
delete head.sessionReferencesRequireTrustedSnapshot;
}
+ delete head.agentReferences;
this.deps.onUserMessageRewritten?.(sessionId, head, {
ghostId: verdict.ghostId,
ghostName: verdict.ghostName,
diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
index f8f32ae39d..4bbf6f7bc7 100644
--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts
+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
@@ -11,6 +11,8 @@
* pending 状态可从 DB 确定性重建(无额外状态列)。
*/
+import { projectPersistedAgentFacingUserText } from '@cindy/maker-shared/agent-input-projection';
+
/** DB 层引擎标识(sessions.agent_kind / messages.agent_kind 的值域)。 */
export type DbAgentKind = 'cc' | 'codex';
@@ -135,7 +137,9 @@ export function extractPlainText(content: unknown): string {
}
if (content && typeof content === 'object') {
const c = content as Record<string, unknown>;
- if (typeof c.text === 'string') return c.text;
+ if (typeof c.text === 'string') {
+ return projectPersistedAgentFacingUserText(c) ?? c.text;
+ }
if (typeof c.message === 'string') return c.message;
}
return '';
diff --git a/apps/desktop/src/main/maker-ipc/agentInputReferences.ts b/apps/desktop/src/main/maker-ipc/agentInputReferences.ts
new file mode 100644
index 0000000000..cd2f797ff7
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/agentInputReferences.ts
@@ -0,0 +1,145 @@
+import { and, eq } from 'drizzle-orm';
+
+import {
+ boundAgentReferenceText,
+ projectPersistedAgentFacingUserText,
+ readAgentInputReferences,
+ type AgentInputReference,
+} from '@cindy/maker-shared/agent-input-projection';
+
+import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';
+import { getDbClient } from '../localDb/client/current.js';
+import { messages, sessions } from '../localDb/schema.js';
+
+import { extractPlainText } from './agentHandoff.js';
+
+type ReferencedMessageLookup =
+ | { state: 'visible'; text: string | null }
+ | { state: 'hidden' }
+ | { state: 'missing' };
+
+async function readReferencedMessageText(
+ sessionId: string,
+ messageClientId: string,
+): Promise<ReferencedMessageLookup> {
+ const [row] = await getDbClient()
+ .drizzle.select({
+ role: messages.role,
+ content: messages.content,
+ createdAt: messages.createdAt,
+ rewindAt: messages.rewindAt,
+ clearedAt: sessions.clearedAt,
+ })
+ .from(messages)
+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))
+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, messageClientId)))
+ .limit(1);
+ if (!row) return { state: 'missing' };
+ if (
+ row.rewindAt != null
+ || (row.clearedAt != null && row.createdAt <= row.clearedAt)
+ ) {
+ return { state: 'hidden' };
+ }
+ const projected = row.role === 'user'
+ ? projectPersistedAgentFacingUserText(row.content)
+ : null;
+ return {
+ state: 'visible',
+ text: (projected ?? extractPlainText(row.content)).trim() || null,
+ };
+}
+
+function persistReferences(
+ persistedContent: string,
+ references: readonly AgentInputReference[],
+): string {
+ try {
+ const parsed = JSON.parse(persistedContent) as unknown;
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return persistedContent;
+ const next = { ...(parsed as Record<string, unknown>) };
+ delete next.agentReferences;
+ return JSON.stringify({
+ ...next,
+ ...(references.length > 0 ? { agentReferences: references } : {}),
+ });
+ } catch {
+ return persistedContent;
+ }
+}
+
+function readPersistedReferences(
+ persistedContent: string,
+ text: string,
+): { present: boolean; references: AgentInputReference[] } {
+ try {
+ const parsed = JSON.parse(persistedContent) as unknown;
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ return { present: false, references: [] };
+ }
+ const record = parsed as Record<string, unknown>;
+ return {
+ present: Object.hasOwn(record, 'agentReferences'),
+ references: readAgentInputReferences(record.agentReferences, text),
+ };
+ } catch {
+ return { present: false, references: [] };
+ }
+}
+
+/**
+ * Validate reference metadata and hydrate missing message bodies from the
+ * authoritative host DB before the queue accepts/persists the item.
+ */
+export async function hydrateQueuedAgentReferences(
+ queued: AgentInputQueuedMessage,
+): Promise<AgentInputQueuedMessage> {
+ const persisted = readPersistedReferences(queued.persistedContent, queued.text);
+ const references = queued.agentReferences !== undefined
+ ? readAgentInputReferences(queued.agentReferences, queued.text)
+ : persisted.references;
+ if (references.length === 0) {
+ if (queued.agentReferences === undefined && !persisted.present) return queued;
+ const sanitized = { ...queued };
+ delete sanitized.agentReferences;
+ sanitized.persistedContent = persistReferences(queued.persistedContent, []);
+ return sanitized;
+ }
+
+ const hydrated = await Promise.all(references.map(async (reference): Promise<AgentInputReference> => {
+ if (reference.kind !== 'message') return reference;
+ let lookup: ReferencedMessageLookup = { state: 'missing' };
+ try {
+ lookup = await readReferencedMessageText(
+ reference.sessionId,
+ reference.messageClientId,
+ );
+ } catch {
+ // Cross-device references may not exist in this host DB. The bounded
+ // Composer-captured body remains a valid fallback.
+ }
+ const sourceText = lookup.state === 'visible'
+ ? lookup.text ?? ''
+ : lookup.state === 'hidden'
+ ? ''
+ : reference.text ?? '';
+ const bounded = boundAgentReferenceText(sourceText);
+ const capturedTruncated = reference.truncated;
+ const base = { ...reference };
+ delete base.text;
+ delete base.truncated;
+ return {
+ ...base,
+ ...(bounded.text ? { text: bounded.text } : {}),
+ ...((lookup.state === 'missing' && capturedTruncated === true) || bounded.truncated
+ ? { truncated: true }
+ : {}),
+ };
+ }));
+
+ return {
+ ...queued,
+ agentReferences: hydrated,
+ persistedContent: persistReferences(queued.persistedContent, hydrated),
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index b50414c91c..02027f941a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -35,6 +35,7 @@ import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm';
import { BrowserWindow, ipcMain } from 'electron';
import type { AgentMeta } from '../../renderer/lib/ccAgent.types';
import {
+ getAgentFacingText,
serializeSessionReferencePayload,
type AgentInputCreateOpts,
type AgentInputQueuedMessage,
@@ -320,6 +321,7 @@ import {
type MakerSessionAgentSwitchHandlerDeps,
} from './sessionAgentSwitchHandler.js';
import { prependHandoffToUserMessage } from './agentHandoff.js';
+import { hydrateQueuedAgentReferences } from './agentInputReferences.js';
import { agentHandoffPending } from './agentHandoffPendingSingleton.js';
import { type MakerSessionCreateOpts, withCreateSessionStderr } from './sessionRequest.js';
import { persistAndHydrateSessionProvider } from './sessionProviderBootstrap.js';
@@ -5894,7 +5896,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
},
// 意识拦截钩(订阅槽①):派发/落库前问已装钩子意识;fail-open 由
// screenGhostUserMessage 内部收敛,快路径(无钩子意识)零开销。
- screenUserMessage: (sessionId, item) => screenGhostUserMessage(sessionId, item.text),
+ screenUserMessage: (sessionId, agentFacingText) =>
+ screenGhostUserMessage(sessionId, agentFacingText),
onUserMessageBlocked: (sessionId, item, verdict) =>
broadcastGhostMessageBlocked({
sessionId,
@@ -6228,7 +6231,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
// 恢复先于入队:普通新输入保持 FIFO;「继续任务」由 coordinator 在完整旧队列
// 恢复后再明确插到队首,避免恢复竞态把它重新压到后面。
await inputCoordinator.ensureQueueRestored(sid).catch(() => undefined);
- const queued = (await materializeQueuedOssAttachments(sid, requireQueuedMessage(item))) as AgentInputQueuedMessage;
+ const queuedWithAttachments = (await materializeQueuedOssAttachments(
+ sid,
+ requireQueuedMessage(item),
+ )) as AgentInputQueuedMessage;
+ const queued = await hydrateQueuedAgentReferences(queuedWithAttachments);
let shouldAutoTitle = false;
if (isDeviceLinkInvoke() && queued.text.trim()) {
try {
@@ -6256,7 +6263,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
scheduleEligibleDeviceLinkAutoTitle({
maker,
sessionId: sid,
- text: queued.text,
+ text: getAgentFacingText(queued),
agentKind: queued.createOpts.agentKind,
});
}
@@ -6286,7 +6293,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
const steerOpts = opts && typeof opts === 'object'
? opts as { removeFromQueue?: boolean; touchUserSend?: boolean }
: undefined;
- const queued = (await materializeQueuedOssAttachments(
+ const queuedWithAttachments = (await materializeQueuedOssAttachments(
sid,
requireQueuedMessage(item, {
// A device-link projection intentionally omits the trusted snapshot.
@@ -6295,6 +6302,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
allowMissingTrustedContexts: isDeviceLinkInvoke() && steerOpts?.removeFromQueue === true,
}),
)) as AgentInputQueuedMessage;
+ const queued = await hydrateQueuedAgentReferences(queuedWithAttachments);
return inputCoordinator.steer(
sid,
queued,
@@ -6389,7 +6397,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
const cid = requireClientId(clientId);
const remote = isDeviceLinkInvoke();
const parsed = requireQueuedMessage(item);
- const queued = (await materializeQueuedOssAttachments(sid, parsed)) as AgentInputQueuedMessage;
+ const queuedWithAttachments = (await materializeQueuedOssAttachments(
+ sid,
+ parsed,
+ )) as AgentInputQueuedMessage;
+ const queued = await hydrateQueuedAgentReferences(queuedWithAttachments);
// 旧 device-link update-content 调用没有 side-channel sessionRefs;显式
// 传空数组,避免 updateQueuedMessageContent 从完整文本重新解析控制端坐标。
const update = remote && parsed.sessionRefs === undefined
diff --git a/apps/desktop/src/main/sessionTaskSummary.logic.ts b/apps/desktop/src/main/sessionTaskSummary.logic.ts
index d0a9c3d571..fa80692ed4 100644
--- a/apps/desktop/src/main/sessionTaskSummary.logic.ts
+++ b/apps/desktop/src/main/sessionTaskSummary.logic.ts
@@ -8,6 +8,7 @@
* 而非平行实现(避免逻辑漂移)。
*/
+import { projectPersistedAgentFacingUserText } from '@cindy/maker-shared/agent-input-projection';
import { isSyntheticTriggerText } from '../shared/interruptedTurn.js';
/** 输出硬上限(字符)——与 prompt 长档上限相同(≤26 字)。实测模型(haiku/mini)
@@ -82,6 +83,8 @@ export function extractText(raw: string | null | undefined, role: string): strin
try {
const parsed: unknown = JSON.parse(raw);
if (role === 'user' && parsed && typeof parsed === 'object' && 'text' in parsed) {
+ const projected = projectPersistedAgentFacingUserText(parsed);
+ if (projected !== null) return guard(projected);
const text = (parsed as { text?: unknown }).text;
return typeof text === 'string' ? guard(text) : '';
}
diff --git a/apps/desktop/src/renderer/__tests__/composerQuoteDocument.test.ts b/apps/desktop/src/renderer/__tests__/composerQuoteDocument.test.ts
index 29c32632db..25efc769f1 100644
--- a/apps/desktop/src/renderer/__tests__/composerQuoteDocument.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerQuoteDocument.test.ts
@@ -218,6 +218,7 @@ describe('composerQuoteDocument', () => {
expect(serialized).toEqual({
text: 'long pasted text',
+ agentReferences: [],
pastedTextRanges: [{ start: 0, end: 16, display: 'Pasted text (1 line)' }],
slashCommandRanges: [],
});
@@ -235,11 +236,42 @@ describe('composerQuoteDocument', () => {
expect(serialized).toEqual({
text: 'long pasted text',
+ agentReferences: [],
pastedTextRanges: [{ start: 0, end: 16, display: 'Pasted text (1 line)' }],
slashCommandRanges: [],
});
});
+ it('projects structured reference offsets through block separators and trimming', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const serialized = serializeComposerContentBlocksWithRanges([
+ {
+ kind: 'text',
+ text: ` inspect ${href}`,
+ agentReferences: [{
+ kind: 'message',
+ start: 10,
+ end: 10 + href.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Complete target message body',
+ }],
+ },
+ ]);
+
+ expect(serialized.text).toBe(`inspect ${href}`);
+ expect(serialized.agentReferences).toEqual([{
+ kind: 'message',
+ start: 8,
+ end: 8 + href.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Complete target message body',
+ }]);
+ });
+
it('projects decorated slash ranges through trimming and quote separators', () => {
const quote = formatQuoteForSend({ text: 'quoted' });
const serialized = serializeComposerContentBlocksWithRanges([
diff --git a/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts b/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts
index fe2d11fbba..eeb0a1a75f 100644
--- a/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts
+++ b/apps/desktop/src/renderer/__tests__/editLastUserMessage.test.ts
@@ -174,8 +174,15 @@ describe('commitEditAndResend', () => {
expect(sendArgs[8]).toBeUndefined();
});
- it('原消息 chip ranges 由编辑框确认未修改后透传到重发 opts', async () => {
+ it('原消息语义引用与 chip ranges 由编辑框确认未修改后透传到重发 opts', async () => {
const { deps } = makeDeps();
+ const agentReferences = [{
+ kind: 'session' as const,
+ start: 0,
+ end: 11,
+ href: 'cindy://session/source',
+ sessionId: 'source',
+ }];
const pastedTextRanges = [{ start: 0, end: 11, display: 'Pasted text (1 line)' }];
await commitEditAndResend(
{
@@ -183,13 +190,14 @@ describe('commitEditAndResend', () => {
clientId: CLIENT_ID,
text: 'pasted body',
fallbackWorkingDir: '/repo',
+ agentReferences,
pastedTextRanges,
slashCommandRanges: [],
},
deps,
);
const sendArgs = (deps.sendMessage as unknown as Mock).mock.calls[0];
- expect(sendArgs[8]).toEqual({ pastedTextRanges, slashCommandRanges: [] });
+ expect(sendArgs[8]).toEqual({ agentReferences, pastedTextRanges, slashCommandRanges: [] });
});
it('session 行 workingDir 为 null 时回落到 fallbackWorkingDir', async () => {
diff --git a/apps/desktop/src/renderer/__tests__/imageRefParseUserContent.test.ts b/apps/desktop/src/renderer/__tests__/imageRefParseUserContent.test.ts
index 1a5dce933d..1f62a64805 100644
--- a/apps/desktop/src/renderer/__tests__/imageRefParseUserContent.test.ts
+++ b/apps/desktop/src/renderer/__tests__/imageRefParseUserContent.test.ts
@@ -455,6 +455,27 @@ describe('parseUserContent — round-trip with localDb mapper simulation', () =>
).toMatchObject({ text: '/unknown', slashCommandRanges: [] });
});
+ it('round-trips structured reference metadata without changing bubble text', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const text = `inspect ${href}`;
+ const references = [{
+ kind: 'message' as const,
+ start: text.indexOf(href),
+ end: text.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Complete target message body',
+ }];
+ const persisted = stringifyUserContent(text, [], [], false, [], [], [], references);
+
+ expect(parseUserContent(JSON.parse(persisted))).toMatchObject({
+ text,
+ agentReferences: references,
+ });
+ expect(JSON.parse(persisted)).toMatchObject({ text, agentReferences: references });
+ });
+
it('drops malformed slash ranges so corrupted history uses legacy compatibility', () => {
const parsed = parseUserContent({
text: 'not-a-command',
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
index 712044c763..f1d78aa586 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
@@ -56,7 +56,30 @@ vi.mock('@/lib/logger', () => ({
}));
vi.mock('@/lib/imageRef', () => ({
- parseUserContent: vi.fn((c: string) => ({ text: c, images: [], files: [] })),
+ parseUserContent: vi.fn((content: unknown) => {
+ let value = content;
+ if (typeof content === 'string' && content.startsWith('{')) {
+ try {
+ value = JSON.parse(content);
+ } catch {
+ // Plain user text that merely starts with "{" remains plain text.
+ }
+ }
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
+ const record = value as Record<string, unknown>;
+ if (typeof record.text === 'string') {
+ return {
+ text: record.text,
+ images: Array.isArray(record.images) ? record.images : [],
+ files: Array.isArray(record.files) ? record.files : [],
+ ...(Array.isArray(record.agentReferences)
+ ? { agentReferences: record.agentReferences }
+ : {}),
+ };
+ }
+ }
+ return { text: String(content), images: [], files: [] };
+ }),
stringifyUserContent: vi.fn((text: string, images = [], files = []) =>
JSON.stringify({ text, images, files }),
),
@@ -902,7 +925,14 @@ describe('makerChatStore text delta batching', () => {
);
});
- it('preserves paste and slash metadata when retrying remote authentication', async () => {
+ it('preserves semantic references, paste and slash metadata when retrying remote authentication', async () => {
+ const agentReferences = [{
+ kind: 'session' as const,
+ start: 0,
+ end: 5,
+ href: 'cindy://session/source',
+ sessionId: 'source',
+ }];
vi.mocked(sessionService.get).mockResolvedValue({
agentKind: 'codex',
remoteHostId: 'remote-host',
@@ -929,6 +959,7 @@ describe('makerChatStore text delta batching', () => {
undefined,
undefined,
{
+ agentReferences,
pastedTextRanges: [{ start: 0, end: 5, display: 'retry' }],
slashCommandRanges: [],
},
@@ -948,12 +979,45 @@ describe('makerChatStore text delta batching', () => {
await flushPromises();
const retried = input.enqueue.mock.calls[0]?.[1];
+ expect(retried?.chatMessage.agentReferences).toEqual(agentReferences);
expect(retried?.chatMessage.pastedTextRanges).toEqual([
{ start: 0, end: 5, display: 'retry' },
]);
expect(retried?.chatMessage.slashCommandRanges).toEqual([]);
});
+ it('restores semantic reference metadata from persisted user messages', () => {
+ const agentReferences = [{
+ kind: 'message' as const,
+ start: 4,
+ end: 44,
+ href: 'cindy://session/source?message=message-1',
+ sessionId: 'source',
+ messageClientId: 'message-1',
+ text: 'referenced body',
+ }];
+ const [mapped] = makerChatStore.__mapServerMessagesForTest([
+ {
+ id: 'row-user-reference',
+ clientId: 'user-reference',
+ sessionId: SESSION_ID,
+ role: 'user',
+ content: JSON.stringify({
+ text: 'see cindy://session/source?message=message-1',
+ agentReferences,
+ }),
+ toolUseId: null,
+ agentMeta: null,
+ createdAt: '2026-07-24T00:00:00.000Z',
+ } satisfies Message,
+ ]);
+
+ expect(mapped).toEqual(expect.objectContaining({
+ content: 'see cindy://session/source?message=message-1',
+ agentReferences,
+ }));
+ });
+
it('uses the main projection to preserve a pre-dispatch message in the queue', async () => {
makerChatStore.sendMessage(SESSION_ID, 'queued', MODEL, EFFORT, PERMISSION_MODE, WORKING_DIR);
await flushPromises();
diff --git a/apps/desktop/src/renderer/__tests__/sessionLinkPaste.test.ts b/apps/desktop/src/renderer/__tests__/sessionLinkPaste.test.ts
index 5b286896c9..47805f7c08 100644
--- a/apps/desktop/src/renderer/__tests__/sessionLinkPaste.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionLinkPaste.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
+import type { Editor } from '@tiptap/core';
import {
+ resolveSessionMessageReferencesForSend,
sanitizeSessionChipTitle,
pastedSessionChipAttrs,
serializeSessionChipText,
@@ -71,7 +73,7 @@ describe('serializeSessionChipText', () => {
).toBe(SESSION_URL);
});
- it('keeps resolved message text display-only', () => {
+ it('keeps resolved message text out of the persisted deep-link wire', () => {
expect(
serializeSessionChipText({
kind: 'session',
@@ -91,3 +93,44 @@ describe('summarizeSessionMessageChipLabel', () => {
expect(summary.endsWith('…')).toBe(true);
});
});
+
+describe('resolveSessionMessageReferencesForSend', () => {
+ it('waits for the full message body and patches semantic attrs before submit serialization', async () => {
+ const chip = {
+ type: { name: 'mentionChip' },
+ attrs: pastedSessionChipAttrs({ href: MESSAGE_URL, label: null }),
+ };
+ const transaction = {
+ setMeta: () => transaction,
+ setNodeMarkup: (_pos: number, _type: unknown, attrs: unknown) => {
+ chip.attrs = attrs as typeof chip.attrs;
+ return transaction;
+ },
+ };
+ const editor = {
+ isDestroyed: false,
+ state: {
+ doc: {
+ descendants: (visit: (node: typeof chip, pos: number) => void) => visit(chip, 1),
+ },
+ tr: transaction,
+ },
+ view: { dispatch: () => undefined },
+ } as unknown as Editor;
+ let release!: (value: string | null) => void;
+ const resolved = new Promise<string | null>((resolve) => {
+ release = resolve;
+ });
+
+ const pending = resolveSessionMessageReferencesForSend(editor, async () => resolved);
+ expect(chip.attrs.agentText).toBeUndefined();
+ release('Full cross-device message body');
+ await pending;
+
+ expect(chip.attrs).toMatchObject({
+ label: 'Full cross-device message body',
+ titled: true,
+ agentText: 'Full cross-device message body',
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts b/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts
index cccbeaf00b..8e6554d201 100644
--- a/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts
+++ b/apps/desktop/src/renderer/__tests__/userMessageEditBox.test.ts
@@ -147,8 +147,16 @@ describe('UserMessageEditBox — idle 发送', () => {
await waitFor(() => expect(editedOverride).toHaveBeenCalledWith({ text: 'edited reply' }));
});
- it('文本未修改时保留长粘贴与 slash ranges,文本修改后丢弃', async () => {
+ it('文本未修改时保留语义引用与 chip ranges,文本修改后丢弃', async () => {
+ const agentReferences = [{
+ kind: 'session' as const,
+ start: 0,
+ end: 13,
+ href: 'cindy://session/source',
+ sessionId: 'source',
+ }];
const ranges = {
+ agentReferences,
pastedTextRanges: [{ start: 0, end: 13, display: 'Pasted text (1 line)' }],
slashCommandRanges: [] as [],
};
@@ -157,6 +165,7 @@ describe('UserMessageEditBox — idle 发送', () => {
await waitFor(() => expect(commitMock).toHaveBeenCalledTimes(1));
expect(commitMock.mock.calls[0][0]).toMatchObject({
text: 'original text',
+ agentReferences,
pastedTextRanges: ranges.pastedTextRanges,
slashCommandRanges: [],
});
@@ -167,13 +176,22 @@ describe('UserMessageEditBox — idle 发送', () => {
fireEvent.change(second.textarea, { target: { value: 'edited text' } });
fireEvent.click(second.sendBtn);
await waitFor(() => expect(commitMock).toHaveBeenCalledTimes(1));
+ expect(commitMock.mock.calls[0][0].agentReferences).toBeUndefined();
expect(commitMock.mock.calls[0][0].pastedTextRanges).toBeUndefined();
expect(commitMock.mock.calls[0][0].slashCommandRanges).toBeUndefined();
});
- it('被拦消息覆盖重发在文本未修改时透传 chip ranges', async () => {
+ it('被拦消息覆盖重发在文本未修改时透传语义引用与 chip ranges', async () => {
const override = vi.fn(async () => {});
+ const agentReferences = [{
+ kind: 'session' as const,
+ start: 0,
+ end: 13,
+ href: 'cindy://session/source',
+ sessionId: 'source',
+ }];
const ranges = {
+ agentReferences,
pastedTextRanges: [{ start: 0, end: 13, display: 'Pasted text (1 line)' }],
slashCommandRanges: [] as [],
};
@@ -186,6 +204,7 @@ describe('UserMessageEditBox — idle 发送', () => {
await waitFor(() =>
expect(override).toHaveBeenCalledWith({
text: 'original text',
+ agentReferences,
pastedTextRanges: ranges.pastedTextRanges,
slashCommandRanges: [],
}),
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index a20cbfd1e9..18b8c10408 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -3369,6 +3369,7 @@ const MessageItem = memo(function MessageItem({
content={message.content}
sessionReferences={message.sessionReferences}
quotesEncoded={message.quotesEncoded}
+ agentReferences={message.agentReferences}
pastedTextRanges={message.pastedTextRanges}
slashCommandRanges={message.slashCommandRanges}
images={message.images}
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 0c2726389e..845a35ee44 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -45,6 +45,7 @@ import type {
MessageAutomationOrigin,
} from '@/lib/ccAgent.types';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
+import type { AgentInputReference } from '../../../shared/agentInputQueue';
import type { PersistedSessionReferenceMetadata } from '../../../shared/sessionReferenceMetadata';
import { buildRewindDraftAttachments } from '@/lib/rewindDraftAttachments';
import {
@@ -128,6 +129,8 @@ interface UserMessageProps {
sessionReferences?: PersistedSessionReferenceMetadata[];
/** chat-text-quote:content 开头 blockquote 为引用功能产出(胶囊化渲染判据)。 */
quotesEncoded?: boolean;
+ /** Hidden semantic reference ranges; preserved only while visible text is unchanged. */
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
images?: UserImageItem[];
@@ -656,6 +659,7 @@ export function UserMessage({
content,
sessionReferences,
quotesEncoded,
+ agentReferences,
pastedTextRanges,
slashCommandRanges,
images,
@@ -1179,6 +1183,7 @@ export function UserMessage({
files={files}
workingDir={workingDir}
quotesEncoded={quotesEncoded}
+ agentReferences={agentReferences}
pastedTextRanges={pastedTextRanges}
slashCommandRanges={slashCommandRanges}
sessionRunning={sessionRunning}
@@ -1194,6 +1199,9 @@ export function UserMessage({
submission.text,
{
...(submission.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(submission.agentReferences?.length
+ ? { agentReferences: submission.agentReferences }
+ : {}),
...(submission.pastedTextRanges?.length
? { pastedTextRanges: submission.pastedTextRanges }
: {}),
diff --git a/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx b/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx
index 54f2d316d5..82dfc11bb6 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx
@@ -39,6 +39,7 @@ import { rewindPreview } from '@/lib/sessionService';
import { commitEditAndResendWithRunningRetry } from '@/lib/editLastUserMessage';
import type { RewindDraftImage } from '@/lib/rewindDraftAttachments';
import type { FileRef, PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
+import type { AgentInputReference } from '../../../shared/agentInputQueue';
// 运行中发送的等待兜底:stop 发出后 renderer 迟迟观察不到 idle(远端断链、
// stop 丢失等)时,超过该时长报错退回编辑态,不让 spinner 永转。
@@ -63,6 +64,8 @@ interface UserMessageEditBoxProps {
/** 原消息带「选中引用」编码标志(引用胶囊渲染门控)。可见文本未修改时
* 原样携带;一旦编辑成 markerless 文本就移除,避免手写 blockquote 被误解析。 */
quotesEncoded?: boolean;
+ /** 原消息语义引用 range;可见文本未修改时原样携带。 */
+ agentReferences?: readonly AgentInputReference[];
/** 原消息长粘贴 range;可见文本未修改时原样携带。 */
pastedTextRanges?: readonly PastedTextRange[];
/** 原消息 slash range;undefined 表示旧消息缺少显式 marker,空数组也需保留。 */
@@ -85,6 +88,7 @@ interface UserMessageEditBoxProps {
onCommitOverride?: (submission: {
text: string;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
}) => Promise<void>;
@@ -99,6 +103,7 @@ export function UserMessageEditBox({
files,
workingDir,
quotesEncoded,
+ agentReferences,
pastedTextRanges,
slashCommandRanges,
sessionRunning,
@@ -169,6 +174,10 @@ export function UserMessageEditBox({
const visibleTextUnchanged = text === initialText;
const submitText = visibleTextUnchanged ? (initialSubmitText ?? text) : text;
const preserveQuoteMetadata = quotesEncoded && visibleTextUnchanged;
+ const preservedAgentReferences =
+ visibleTextUnchanged && agentReferences && agentReferences.length > 0
+ ? [...agentReferences]
+ : undefined;
const preservedPastedTextRanges =
visibleTextUnchanged && pastedTextRanges && pastedTextRanges.length > 0
? [...pastedTextRanges]
@@ -182,6 +191,7 @@ export function UserMessageEditBox({
await onCommitOverride({
text: submitText,
...(preserveQuoteMetadata ? { quotesEncoded: true } : {}),
+ ...(preservedAgentReferences ? { agentReferences: preservedAgentReferences } : {}),
...(preservedPastedTextRanges ? { pastedTextRanges: preservedPastedTextRanges } : {}),
...(preservedSlashCommandRanges !== undefined ? { slashCommandRanges: preservedSlashCommandRanges } : {}),
});
@@ -194,6 +204,7 @@ export function UserMessageEditBox({
files,
fallbackWorkingDir: workingDir,
...(preserveQuoteMetadata ? { quotesEncoded: true } : {}),
+ ...(preservedAgentReferences ? { agentReferences: preservedAgentReferences } : {}),
...(preservedPastedTextRanges ? { pastedTextRanges: preservedPastedTextRanges } : {}),
...(preservedSlashCommandRanges !== undefined ? { slashCommandRanges: preservedSlashCommandRanges } : {}),
});
@@ -222,7 +233,7 @@ export function UserMessageEditBox({
submittingRef.current = false;
setSubmitting(false);
}
- }, [sessionId, messageClientId, text, initialText, initialSubmitText, images, files, workingDir, quotesEncoded, pastedTextRanges, slashCommandRanges, onSent, onCommitOverride, t]);
+ }, [sessionId, messageClientId, text, initialText, initialSubmitText, images, files, workingDir, quotesEncoded, agentReferences, pastedTextRanges, slashCommandRanges, onSent, onCommitOverride, t]);
const handleSend = useCallback(() => {
if (!canSend || submittingRef.current) return;
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 88dae855e6..81709a78f9 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -14,6 +14,7 @@ import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router-dom';
import { Folder, MessageSquarePlus, Mic, Pen, TriangleAlert, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
+import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
import { requiresFullAccessConfirmation } from '@cindy/maker-shared/permission-mode';
import { ImageLightbox } from '@/components/chat/ImageLightbox';
import { TextLightbox } from '@/components/chat/TextLightbox';
@@ -56,6 +57,11 @@ import {
type BrowserCommentDraftItem,
} from '@/lib/browserComments';
import { formatMentionRef } from '@/lib/mentionRefFormat';
+import {
+ parseProjectDeepLinkHref,
+ parseSessionDeepLinkHref,
+ projectDisplayName,
+} from '@/lib/deepLink';
import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';
import { shouldOpenTextLightbox } from '@/lib/filePreview';
import {
@@ -114,6 +120,7 @@ import {
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
import {
pastedSessionChipAttrs,
+ resolveSessionMessageReferencesForSend,
serializeSessionChipText,
resolveSessionChipTitles,
} from './sessionLinkPaste';
@@ -250,6 +257,8 @@ interface ChatInputProps {
providerId?: string | null;
/** chat-text-quote:message 开头的 blockquote 为引用功能拼接产出。 */
quotesEncoded?: boolean;
+ /** Ordered semantic projection metadata for session/project/message chips. */
+ agentReferences?: AgentInputReference[];
/** Local display ranges for sent long-paste chips; never added to Agent text. */
pastedTextRanges?: PastedTextRange[];
/** Exact local display ranges for slash commands confirmed by this composer. */
@@ -652,6 +661,7 @@ function serializeEditorContent(editor: Editor): {
text: string;
mentions: MentionedResource[];
hasQuotes: boolean;
+ agentReferences: AgentInputReference[];
pastedTextRanges: PastedTextRange[];
slashCommandRanges: SlashCommandRange[];
} {
@@ -683,6 +693,7 @@ function serializeEditorContent(editor: Editor): {
}
if (pNode.type.name !== 'paragraph') return;
let buf = '';
+ let bufAgentReferences: AgentInputReference[] = [];
let bufPastedTextRanges: PastedTextRange[] = [];
let bufSlashCommandRanges: SlashCommandRange[] = [];
let emittedInlineSegment = false;
@@ -691,10 +702,12 @@ function serializeEditorContent(editor: Editor): {
blocks.push({
kind: 'text',
text: buf,
+ ...(bufAgentReferences.length > 0 ? { agentReferences: bufAgentReferences } : {}),
...(bufPastedTextRanges.length > 0 ? { pastedTextRanges: bufPastedTextRanges } : {}),
...(bufSlashCommandRanges.length > 0 ? { slashCommandRanges: bufSlashCommandRanges } : {}),
});
buf = '';
+ bufAgentReferences = [];
bufPastedTextRanges = [];
bufSlashCommandRanges = [];
emittedInlineSegment = true;
@@ -718,11 +731,48 @@ function serializeEditorContent(editor: Editor): {
} else if (attrs.kind === 'session') {
// 会话深链 chip:有标题 → `[标题](href)`(消息侧 / 手机端 markdown
// 链路显式 label 优先),标题未解析 → 裸 href。
- buf += serializeSessionChipText(attrs);
+ const wire = serializeSessionChipText(attrs);
+ const start = buf.length;
+ buf += wire;
+ const target = parseSessionDeepLinkHref(attrs.path);
+ if (target?.messageClientId) {
+ bufAgentReferences.push({
+ kind: 'message',
+ start,
+ end: buf.length,
+ href: attrs.path,
+ sessionId: target.sessionId,
+ messageClientId: target.messageClientId,
+ ...(attrs.agentText ? { text: attrs.agentText } : {}),
+ ...(attrs.agentTextTruncated ? { truncated: true } : {}),
+ });
+ } else if (target) {
+ bufAgentReferences.push({
+ kind: 'session',
+ start,
+ end: buf.length,
+ href: attrs.path,
+ sessionId: target.sessionId,
+ ...(attrs.titled && attrs.label ? { title: attrs.label } : {}),
+ });
+ }
} else if (attrs.kind === 'project') {
// 项目深链 chip:同 session 的取舍——显式标题走 markdown 形式,
// 目录名占位是 href 可推导的,裸 href 即可(消息侧自行取 basename)。
- buf += serializeProjectChipText(attrs);
+ const wire = serializeProjectChipText(attrs);
+ const start = buf.length;
+ buf += wire;
+ const target = parseProjectDeepLinkHref(attrs.path);
+ if (target) {
+ bufAgentReferences.push({
+ kind: 'project',
+ start,
+ end: buf.length,
+ href: attrs.path,
+ name: attrs.label || projectDisplayName(target.workingDir),
+ workingDir: target.workingDir,
+ });
+ }
} else if (attrs.kind === 'dir') {
// 含空格的 path 用 `@"..."` 引号形式序列化(formatMentionRef),否则
// 下游 `@\S+` 切词会从空格处把 chip 截断。dir 的尾 `/` 一并纳入引号内,
@@ -3349,10 +3399,20 @@ export function ChatInput({
if (!editor) return;
if (disabled) return;
if (dispatchSendInFlightRef.current) return;
+ dispatchSendInFlightRef.current = true;
+ setSendDispatchInFlight(true);
+ try {
+ await resolveSessionMessageReferencesForSend(editor);
+ } finally {
+ dispatchSendInFlightRef.current = false;
+ setSendDispatchInFlight(false);
+ }
+ if (editor.isDestroyed) return;
const {
text: editorText,
mentions,
hasQuotes,
+ agentReferences,
pastedTextRanges,
slashCommandRanges,
} = serializeEditorContent(editor);
@@ -3451,6 +3511,7 @@ export function ChatInput({
deliveryMode,
providerId: sendProviderId,
...(hasQuotes ? { quotesEncoded: true } : {}),
+ ...(agentReferences.length > 0 ? { agentReferences } : {}),
...(pastedTextRanges.length > 0 ? { pastedTextRanges } : {}),
slashCommandRanges,
...(usedGhost ? { onAccepted: markRecentPluginUsage } : {}),
diff --git a/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx b/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx
index 77570200ff..58917d7b10 100644
--- a/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx
@@ -30,6 +30,9 @@ export interface MentionChipAttrs {
path: string;
/** Resolved session/project labels serialize as explicit Markdown labels. */
titled?: boolean;
+ /** Readable target message body for the agent-facing projection. */
+ agentText?: string;
+ agentTextTruncated?: boolean;
}
function displayLabel(attrs: MentionChipAttrs): string {
@@ -84,6 +87,8 @@ function MentionChipNodeView({ node, selected }: NodeViewProps) {
data-label={attrs.label}
data-path={attrs.path}
data-titled={attrs.titled ? 'true' : undefined}
+ data-agent-text={attrs.agentText}
+ data-agent-text-truncated={attrs.agentTextTruncated ? 'true' : undefined}
data-drag-handle=""
draggable={true}
contentEditable={false}
@@ -137,6 +142,20 @@ export const MentionChipNode = Node.create<Record<string, never>, Record<string,
parseHTML: (element) => element.getAttribute('data-titled') === 'true',
renderHTML: (attrs) => (attrs.titled ? { 'data-titled': 'true' } : {}),
},
+ agentText: {
+ default: undefined,
+ parseHTML: (element) => element.getAttribute('data-agent-text'),
+ renderHTML: (attrs) => (
+ typeof attrs.agentText === 'string' ? { 'data-agent-text': attrs.agentText } : {}
+ ),
+ },
+ agentTextTruncated: {
+ default: undefined,
+ parseHTML: (element) => element.getAttribute('data-agent-text-truncated') === 'true',
+ renderHTML: (attrs) => (
+ attrs.agentTextTruncated ? { 'data-agent-text-truncated': 'true' } : {}
+ ),
+ },
};
},
diff --git a/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts b/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts
index 56bb608cbb..51143ec104 100644
--- a/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts
+++ b/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts
@@ -8,7 +8,8 @@
* - 整段会话裸 URL → 先显示短会话 ID 占位(titled=false),随后
* `resolveSessionChipTitles` 异步查到标题后原地 patch 节点 attrs;
* - 消息锚点始终忽略会话标题/markdown label,异步读取目标消息正文,
- * 发送时仍只序列化原始深链,不把正文复制进当前消息。
+ * wire text 仍序列化原始深链,同时把有上限的完整正文放进结构化
+ * agent reference metadata;compact label 只负责 UI 展示。
* (addToHistory:false,不污染撤销栈)——先占位再增量刷新,不产生
* 空白帧 / 跳变(设计规范规则 7)。
*
@@ -18,13 +19,14 @@
* ASCII 方括号会破坏 markdown 链接语法,清洗为空格。
*/
import type { Editor } from '@tiptap/core';
+import { boundAgentReferenceText } from '@cindy/maker-shared/agent-input-projection';
import { parseSessionDeepLinkHref } from '@/lib/deepLink';
import { shortSessionId } from '@/lib/sessionId';
import type { MentionChipAttrs } from './MentionChipNode';
-/** Draft / DOM attrs only keep a compact message summary; full text lives in tooltip state. */
+/** Visible chip labels stay compact; the full bounded body is separate semantic metadata. */
export const SESSION_MESSAGE_CHIP_LABEL_MAX_CHARS = 240;
export function summarizeSessionMessageChipLabel(text: string): string {
@@ -101,6 +103,90 @@ export async function resolvePastedSessionTitle(sessionId: string): Promise<stri
return remote?.title?.trim() || null;
}
+const pendingMessageResolutions = new WeakMap<Editor, Map<string, Promise<void>>>();
+
+function patchResolvedMessageChip(editor: Editor, path: string, value: string): void {
+ const display = summarizeSessionMessageChipLabel(value);
+ if (!display || editor.isDestroyed) return;
+ const agentText = boundAgentReferenceText(value);
+ const tr = editor.state.tr;
+ let changed = false;
+ editor.state.doc.descendants((node, pos) => {
+ if (node.type.name !== 'mentionChip') return;
+ const attrs = node.attrs as MentionChipAttrs;
+ if (attrs.kind !== 'session' || attrs.path !== path) return;
+ tr.setNodeMarkup(pos, undefined, {
+ ...attrs,
+ label: display,
+ titled: true,
+ agentText: agentText.text,
+ ...(agentText.truncated ? { agentTextTruncated: true } : {}),
+ });
+ changed = true;
+ });
+ if (!changed) return;
+ tr.setMeta('addToHistory', false);
+ editor.view.dispatch(tr);
+}
+
+function resolveMessageChip(
+ editor: Editor,
+ path: string,
+ target: NonNullable<ReturnType<typeof parseSessionDeepLinkHref>>,
+ resolveMessageText: (sessionId: string, clientId: string) => Promise<string | null>,
+): Promise<void> {
+ let editorPending = pendingMessageResolutions.get(editor);
+ if (!editorPending) {
+ editorPending = new Map();
+ pendingMessageResolutions.set(editor, editorPending);
+ }
+ const existing = editorPending.get(path);
+ if (existing) return existing;
+
+ const pending = resolveMessageText(target.sessionId, target.messageClientId!)
+ .then((value) => {
+ if (value) patchResolvedMessageChip(editor, path, value);
+ })
+ .catch(() => {
+ // Keep the short-id placeholder when the target is unavailable.
+ })
+ .finally(() => {
+ editorPending?.delete(path);
+ if (editorPending?.size === 0) pendingMessageResolutions.delete(editor);
+ });
+ editorPending.set(path, pending);
+ return pending;
+}
+
+/**
+ * Resolve every message chip that still lacks a bounded semantic body.
+ * Sending awaits this so a fast submit cannot outrun cross-device hydration.
+ */
+export async function resolveSessionMessageReferencesForSend(
+ editor: Editor,
+ resolveMessageText: (
+ sessionId: string,
+ clientId: string,
+ ) => Promise<string | null> = resolvePastedSessionMessageText,
+): Promise<void> {
+ const pendingTargets = new Map<
+ string,
+ NonNullable<ReturnType<typeof parseSessionDeepLinkHref>>
+ >();
+ editor.state.doc.descendants((node) => {
+ if (node.type.name !== 'mentionChip') return;
+ const attrs = node.attrs as MentionChipAttrs;
+ if (attrs.kind !== 'session' || attrs.agentText) return;
+ const target = parseSessionDeepLinkHref(attrs.path);
+ if (target?.messageClientId) pendingTargets.set(attrs.path, target);
+ });
+ await Promise.all(
+ [...pendingTargets].map(([path, target]) => (
+ resolveMessageChip(editor, path, target, resolveMessageText)
+ )),
+ );
+}
+
/**
* 扫描编辑器里所有未解析标题(titled=false)的 session chip,异步查标题后
* 原地 patch 节点 attrs。要点:
@@ -118,6 +204,7 @@ export function resolveSessionChipTitles(
clientId: string,
) => Promise<string | null> = resolvePastedSessionMessageText,
): void {
+ void resolveSessionMessageReferencesForSend(editor, resolveMessageText);
const pendingTargets = new Map<
string,
NonNullable<ReturnType<typeof parseSessionDeepLinkHref>>
@@ -127,19 +214,12 @@ export function resolveSessionChipTitles(
const attrs = node.attrs as MentionChipAttrs;
if (attrs.kind !== 'session' || attrs.titled) return;
const target = parseSessionDeepLinkHref(attrs.path);
- if (target) pendingTargets.set(attrs.path, target);
+ if (target && !target.messageClientId) pendingTargets.set(attrs.path, target);
});
for (const [path, target] of pendingTargets) {
- const resolved = target.messageClientId
- ? resolveMessageText(target.sessionId, target.messageClientId)
- : resolveTitle(target.sessionId);
- void resolved
+ void resolveTitle(target.sessionId)
.then((value) => {
- const display = target.messageClientId
- ? summarizeSessionMessageChipLabel(value ?? '')
- : value
- ? sanitizeSessionChipTitle(value)
- : '';
+ const display = value ? sanitizeSessionChipTitle(value) : '';
if (!display || editor.isDestroyed) return;
const tr = editor.state.tr;
let changed = false;
@@ -148,7 +228,11 @@ export function resolveSessionChipTitles(
const attrs = node.attrs as MentionChipAttrs;
if (attrs.kind !== 'session' || attrs.titled) return;
if (attrs.path !== path) return;
- tr.setNodeMarkup(pos, undefined, { ...attrs, label: display, titled: true });
+ tr.setNodeMarkup(pos, undefined, {
+ ...attrs,
+ label: display,
+ titled: true,
+ });
changed = true;
});
if (!changed) return;
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 32765ecb62..8ef109f95f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -25,6 +25,7 @@ import {
import type { CSSProperties, ReactNode } from 'react';
import { useLocation, useNavigate, useOutletContext, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
+import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
import { useProportionalWidth } from '@/hooks/useProportionalWidth';
import { setBlockExpanded } from '@/hooks/useExpandedBlockMemory';
import {
@@ -1051,6 +1052,7 @@ export function CCAgentSessionView({
mentions?: MentionedResource[];
/** 正文前缀含「选中引用」编码块——补选目录后的派发同样要携带,否则该消息持久化后渲染不出胶囊。 */
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
} | null>(null);
@@ -1849,6 +1851,7 @@ export function CCAgentSessionView({
files,
mentions,
quotesEncoded,
+ agentReferences,
pastedTextRanges,
slashCommandRanges,
} = pendingSendRef.current;
@@ -1861,9 +1864,10 @@ export function CCAgentSessionView({
newDir,
files,
mentions,
- quotesEncoded || pastedTextRanges?.length || slashCommandRanges !== undefined
+ quotesEncoded || agentReferences?.length || pastedTextRanges?.length || slashCommandRanges !== undefined
? {
...(quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(agentReferences?.length ? { agentReferences } : {}),
...(pastedTextRanges?.length ? { pastedTextRanges } : {}),
...(slashCommandRanges !== undefined ? { slashCommandRanges } : {}),
}
@@ -2100,6 +2104,7 @@ export function CCAgentSessionView({
opts?: {
deliveryMode?: MessageDeliveryMode;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
},
@@ -2158,6 +2163,7 @@ export function CCAgentSessionView({
files,
mentions,
...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(opts?.agentReferences?.length ? { agentReferences: opts.agentReferences } : {}),
...(opts?.pastedTextRanges?.length ? { pastedTextRanges: opts.pastedTextRanges } : {}),
...(opts?.slashCommandRanges !== undefined
? { slashCommandRanges: opts.slashCommandRanges }
@@ -2199,6 +2205,7 @@ export function CCAgentSessionView({
return dispatch(message, model, effort, permissionMode, session.workingDir, files, mentions, {
...orcaLeadVendorOptions,
...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(opts?.agentReferences?.length ? { agentReferences: opts.agentReferences } : {}),
...(opts?.pastedTextRanges?.length ? { pastedTextRanges: opts.pastedTextRanges } : {}),
...(opts?.slashCommandRanges !== undefined
? { slashCommandRanges: opts.slashCommandRanges }
@@ -2422,11 +2429,15 @@ export function CCAgentSessionView({
pending.mentions,
pending.vendorOptions ||
pending.quotesEncoded ||
+ pending.agentReferences?.length ||
pending.pastedTextRanges?.length ||
pending.slashCommandRanges !== undefined
? {
...(pending.vendorOptions ? { vendorOptions: pending.vendorOptions } : {}),
...(pending.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(pending.agentReferences?.length
+ ? { agentReferences: pending.agentReferences }
+ : {}),
...(pending.pastedTextRanges?.length
? { pastedTextRanges: pending.pastedTextRanges }
: {}),
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index e0a56d9431..8514b3c809 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -115,6 +115,7 @@ import {
import type { Effort, PermissionMode } from '@/lib/userPreferences.types';
import type { AttachedFile, MentionedResource } from '@/lib/fileTypes';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
+import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
import { toast } from '@/lib/toast';
import { cn } from '@/lib/utils';
import { InvisibleWindowDragStrip } from '@/components/layout/windowDrag';
@@ -1156,6 +1157,7 @@ export function NewMakerDraftRoute() {
opts?: {
providerId?: string | null;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
onAccepted?: () => void;
@@ -1306,6 +1308,7 @@ export function NewMakerDraftRoute() {
files: rehydratedFiles,
mentions,
...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(opts?.agentReferences?.length ? { agentReferences: opts.agentReferences } : {}),
...(opts?.pastedTextRanges?.length
? { pastedTextRanges: opts.pastedTextRanges }
: {}),
@@ -1521,6 +1524,9 @@ export function NewMakerDraftRoute() {
mentions,
{
...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(opts?.agentReferences?.length
+ ? { agentReferences: opts.agentReferences }
+ : {}),
...(opts?.pastedTextRanges?.length
? { pastedTextRanges: opts.pastedTextRanges }
: {}),
@@ -1621,6 +1627,7 @@ export function NewMakerDraftRoute() {
files: rehydratedFiles,
mentions,
...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(opts?.agentReferences?.length ? { agentReferences: opts.agentReferences } : {}),
...(opts?.pastedTextRanges?.length ? { pastedTextRanges: opts.pastedTextRanges } : {}),
...(opts?.slashCommandRanges !== undefined
? { slashCommandRanges: opts.slashCommandRanges }
diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
index 38c5c626f2..82f812a924 100644
--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts
@@ -48,6 +48,7 @@ import {
import type { ChatDisplaySnapshot } from '@/components/chat/ChatDisplaySnapshotContext';
import type { AttachedFile, MentionedResource } from '@/lib/fileTypes';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
+import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
import { createLogger } from '@/lib/logger';
const log = createLogger('UseCCAgentChat');
@@ -115,6 +116,7 @@ interface UseCCAgentChatReturn {
opts?: {
vendorOptions?: Record<string, unknown>;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
},
@@ -137,6 +139,7 @@ interface UseCCAgentChatReturn {
opts?: {
vendorOptions?: Record<string, unknown>;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
},
@@ -368,6 +371,7 @@ export function useCCAgentChat(
opts?: {
vendorOptions?: Record<string, unknown>;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
},
@@ -421,6 +425,7 @@ export function useCCAgentChat(
opts?: {
vendorOptions?: Record<string, unknown>;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
},
diff --git a/apps/desktop/src/renderer/lib/composerQuoteDocument.ts b/apps/desktop/src/renderer/lib/composerQuoteDocument.ts
index 0d517d05ae..2ac934c060 100644
--- a/apps/desktop/src/renderer/lib/composerQuoteDocument.ts
+++ b/apps/desktop/src/renderer/lib/composerQuoteDocument.ts
@@ -8,6 +8,7 @@
* draft store deterministic and directly testable.
*/
import type { JSONContent } from '@tiptap/core';
+import type { AgentInputReference } from '../../shared/agentInputQueue';
import { parseChatQuoteSegments, type ChatQuote, type ChatQuoteSegment } from '@/lib/chatQuotes';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
@@ -23,6 +24,8 @@ export interface ComposerQuoteAttrs {
export interface ComposerSerializedBlock {
kind: 'text' | 'quote';
text: string;
+ /** Structured reference offsets relative to this block's text. */
+ agentReferences?: AgentInputReference[];
/** Ranges are relative to this block's text. */
pastedTextRanges?: PastedTextRange[];
/** Ranges are relative to this block's text. */
@@ -211,10 +214,12 @@ export function serializeComposerContentBlocksWithRanges(
blocks: readonly ComposerSerializedBlock[],
): {
text: string;
+ agentReferences: AgentInputReference[];
pastedTextRanges: PastedTextRange[];
slashCommandRanges: SlashCommandRange[];
} {
let serialized = '';
+ const agentReferences: AgentInputReference[] = [];
const pastedTextRanges: PastedTextRange[] = [];
const slashCommandRanges: SlashCommandRange[] = [];
let previousKind: ComposerSerializedBlock['kind'] | null = null;
@@ -244,6 +249,13 @@ export function serializeComposerContentBlocksWithRanges(
serialized += separator;
const blockStart = serialized.length;
serialized += block.text;
+ for (const reference of block.agentReferences ?? []) {
+ agentReferences.push({
+ ...reference,
+ start: blockStart + reference.start,
+ end: blockStart + reference.end,
+ });
+ }
for (const range of block.pastedTextRanges ?? []) {
pastedTextRanges.push({
start: blockStart + range.start,
@@ -265,6 +277,12 @@ export function serializeComposerContentBlocksWithRanges(
const text = serialized.trim();
return {
text,
+ agentReferences: agentReferences
+ .map((reference) => {
+ const trimmed = trimRangeToText(reference, leadingTrim, text.length);
+ return trimmed ? { ...reference, ...trimmed } : null;
+ })
+ .filter((reference): reference is AgentInputReference => reference !== null),
pastedTextRanges: pastedTextRanges
.map((range) => {
const trimmed = trimRangeToText(range, leadingTrim, text.length);
diff --git a/apps/desktop/src/renderer/lib/editLastUserMessage.ts b/apps/desktop/src/renderer/lib/editLastUserMessage.ts
index 6148599dfe..e1328f3f10 100644
--- a/apps/desktop/src/renderer/lib/editLastUserMessage.ts
+++ b/apps/desktop/src/renderer/lib/editLastUserMessage.ts
@@ -48,6 +48,7 @@ import {
import type { AttachedFile } from '@/lib/fileTypes';
import type { FileRef, PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
import type { Session } from '@/lib/ccAgent.types';
+import type { AgentInputReference } from '../../shared/agentInputQueue';
export interface CommitEditAndResendOptions {
sessionId: string;
@@ -65,6 +66,8 @@ export interface CommitEditAndResendOptions {
* 标志门控,丢掉会让 markdown blockquote 退回普通文本展示。
*/
quotesEncoded?: boolean;
+ /** 原消息语义引用 range;只有编辑框确认可见文本未改变时才传入。 */
+ agentReferences?: AgentInputReference[];
/** 原消息长粘贴 range;只有编辑框确认文本未改变时才传入。 */
pastedTextRanges?: PastedTextRange[];
/** 原消息 slash range;undefined 表示缺少显式 range,空数组表示明确无 slash。 */
@@ -243,9 +246,13 @@ export async function commitEditAndResend(
session.workingDir ?? opts.fallbackWorkingDir,
attachments.length > 0 ? attachments : undefined,
undefined,
- opts.quotesEncoded || opts.pastedTextRanges?.length || opts.slashCommandRanges !== undefined
+ opts.quotesEncoded ||
+ opts.agentReferences?.length ||
+ opts.pastedTextRanges?.length ||
+ opts.slashCommandRanges !== undefined
? {
...(opts.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(opts.agentReferences?.length ? { agentReferences: opts.agentReferences } : {}),
...(opts.pastedTextRanges?.length ? { pastedTextRanges: opts.pastedTextRanges } : {}),
...(opts.slashCommandRanges !== undefined ? { slashCommandRanges: opts.slashCommandRanges } : {}),
}
diff --git a/apps/desktop/src/renderer/lib/imageRef.ts b/apps/desktop/src/renderer/lib/imageRef.ts
index 4a4f8bb0e7..50effeda8f 100644
--- a/apps/desktop/src/renderer/lib/imageRef.ts
+++ b/apps/desktop/src/renderer/lib/imageRef.ts
@@ -18,6 +18,10 @@ import {
parsePersistedSessionReferenceMetadata,
type PersistedSessionReferenceMetadata,
} from '../../shared/sessionReferenceMetadata';
+import {
+ readAgentInputReferences,
+ type AgentInputReference,
+} from '@cindy/maker-shared/agent-input-projection';
export interface ImageRef {
/** Custom-protocol URL: 'xdt-image://{sessionId}/{filename}'. */
@@ -89,6 +93,8 @@ export interface UserMessageContent {
* the history renderer must not fall back to its legacy line-start heuristic.
*/
slashCommandRanges?: SlashCommandRange[];
+ /** Hidden semantic projection metadata; message bubbles still render `text`. */
+ agentReferences?: AgentInputReference[];
}
/**
@@ -159,6 +165,7 @@ export function parseUserContent(content: unknown): UserMessageContent {
const sessionReferences = parsePersistedSessionReferenceMetadata(obj.sessionReferences);
const pastedTextRanges = coercePastedTextRanges(obj.pastedTextRanges, obj.text);
const slashCommandRanges = coerceSlashCommandRanges(obj.slashCommandRanges, obj.text);
+ const agentReferences = readAgentInputReferences(obj.agentReferences, obj.text);
return {
text: obj.text,
images,
@@ -167,6 +174,7 @@ export function parseUserContent(content: unknown): UserMessageContent {
...(obj.quotesEncoded === true ? { quotesEncoded: true } : {}),
...(pastedTextRanges.length > 0 ? { pastedTextRanges } : {}),
...(slashCommandRanges !== null ? { slashCommandRanges } : {}),
+ ...(agentReferences.length > 0 ? { agentReferences } : {}),
};
}
// Truly unknown object shape — preserve old defensive stringify behaviour.
@@ -325,6 +333,7 @@ export function stringifyUserContent(
pastedTextRangesOrSessionReferences: PastedTextRange[] | PersistedSessionReferenceMetadata[] = [],
slashCommandRanges?: SlashCommandRange[],
sessionReferences: PersistedSessionReferenceMetadata[] = [],
+ agentReferences: AgentInputReference[] = [],
): string {
const fifthArgIsSessionReferences =
pastedTextRangesOrSessionReferences.length > 0 &&
@@ -347,5 +356,6 @@ export function stringifyUserContent(
...(resolvedSessionReferences.length > 0
? { sessionReferences: resolvedSessionReferences }
: {}),
+ ...(agentReferences.length > 0 ? { agentReferences } : {}),
});
}
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index df327f020a..f843683e2c 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -30,8 +30,12 @@ import type {
AgentInputProjection,
AgentInputQueuedMessage,
AgentInputSessionRef,
+ AgentInputReference,
+} from '../../shared/agentInputQueue';
+import {
+ getAgentFacingText,
+ reconcileSessionRefsForText,
} from '../../shared/agentInputQueue';
-import { reconcileSessionRefsForText } from '../../shared/agentInputQueue';
import { providerSecretStorageKey } from '../../shared/providerSecrets';
import { GHOST_HOST_NOTICE_KEYS } from '../../shared/ghost';
import * as messageService from '@/lib/messageService';
@@ -188,6 +192,8 @@ export interface ChatMessage {
clientId: string;
/** chat-text-quote:开头 blockquote 为引用功能产出(渲染判据),见 imageRef.ts。 */
quotesEncoded?: boolean;
+ /** Hidden semantic projection metadata for rich user-message references. */
+ agentReferences?: AgentInputReference[];
/** Local display metadata; the Agent receives `content` without markers. */
pastedTextRanges?: PastedTextRange[];
/** Exact slash ranges; empty means the composer confirmed no slash command. */
@@ -3160,6 +3166,7 @@ function initGlobalListeners(): void {
retryFiles,
retryMentions,
{
+ agentReferences: lastUser?.agentReferences,
pastedTextRanges: lastUser?.pastedTextRanges,
slashCommandRanges: lastUser?.slashCommandRanges,
authRetryPersistOnProjectionError: {
@@ -5115,6 +5122,7 @@ function buildQueuedMessage(
vendorOptions?: Record<string, unknown>;
/** chat-text-quote:text 开头 blockquote 为引用功能拼接产出(渲染判据)。 */
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
authRetryPersistOnProjectionError?: {
@@ -5146,6 +5154,7 @@ function buildQueuedMessage(
isStreaming: false,
createdAt: new Date().toISOString(),
...(opts?.quotesEncoded === true && { quotesEncoded: true }),
+ ...(opts?.agentReferences?.length && { agentReferences: opts.agentReferences }),
...(opts?.pastedTextRanges?.length && { pastedTextRanges: opts.pastedTextRanges }),
...(opts?.slashCommandRanges !== undefined && {
slashCommandRanges: opts.slashCommandRanges,
@@ -5168,6 +5177,8 @@ function buildQueuedMessage(
opts?.quotesEncoded === true,
opts?.pastedTextRanges,
opts?.slashCommandRanges,
+ [],
+ opts?.agentReferences,
);
return {
@@ -5182,6 +5193,7 @@ function buildQueuedMessage(
files: serializedFiles,
mentions,
...(sessionRefs.length > 0 ? { sessionRefs } : {}),
+ agentReferences: opts?.agentReferences,
chatMessage,
createOpts,
userName: currentUserName,
@@ -5431,6 +5443,7 @@ type SendMessageOpts = {
vendorOptions?: Record<string, unknown>;
/** 本条消息正文前缀含「选中引用」编码块,渲染侧据此启用胶囊化解析。 */
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
authRetryPersistOnProjectionError?: {
@@ -5548,12 +5561,12 @@ async function sendMessageCore(
// 用 Claude haiku 起标题:纯 Codex 用户(无 Claude 鉴权)会 oneShot 失败 →
// fallback 原话,表现为"Codex 会话标题没有智能总结"。current.agentKind 已是
// maker 格式('claude-code' | 'codex'),直接透传。起名走宽限期 + 后台覆盖。
- scheduleAutoName(sessionId, text, current.agentKind);
+ scheduleAutoName(sessionId, getAgentFacingText(queued), current.agentKind);
} else {
// fork-auto-name: fork 出来的会话带着占位标题 "[Fork] <源标题>",在用户
// 于新会话里发出第一句话时按同款流程基于这句话改名(fork 会话天然带历史
// 消息,isFirstMessage=false 走不到上面的分支)。
- maybeAutoNameForkedSession(sessionId, text);
+ maybeAutoNameForkedSession(sessionId, getAgentFacingText(queued));
}
// 视觉连续性: agent 空闲 + 队列为空时, main coordinator 会立即派发这条(见
@@ -5660,6 +5673,7 @@ function steerMessage(
opts?: {
vendorOptions?: Record<string, unknown>;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
},
@@ -5723,6 +5737,7 @@ function steerMessageCore(
opts?: {
vendorOptions?: Record<string, unknown>;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
},
@@ -5792,6 +5807,7 @@ async function resendBlockedMessage(
newText: string,
opts?: {
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
},
@@ -5821,9 +5837,15 @@ async function resendBlockedMessage(
row.workingDir,
msg.retryFiles,
msg.retryMentions,
- opts?.quotesEncoded || opts?.pastedTextRanges?.length || opts?.slashCommandRanges !== undefined
+ opts?.quotesEncoded ||
+ opts?.agentReferences?.length ||
+ opts?.pastedTextRanges?.length ||
+ opts?.slashCommandRanges !== undefined
? {
...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(opts?.agentReferences?.length
+ ? { agentReferences: opts.agentReferences }
+ : {}),
...(opts?.pastedTextRanges?.length ? { pastedTextRanges: opts.pastedTextRanges } : {}),
...(opts?.slashCommandRanges !== undefined ? { slashCommandRanges: opts.slashCommandRanges } : {}),
}
@@ -7826,6 +7848,9 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {
...(parsed.images.length > 0 && { images: parsed.images }),
...(parsed.files.length > 0 && { files: parsed.files }),
...(parsed.quotesEncoded === true && { quotesEncoded: true }),
+ ...(parsed.agentReferences?.length && {
+ agentReferences: parsed.agentReferences,
+ }),
...(parsed.pastedTextRanges?.length && {
pastedTextRanges: parsed.pastedTextRanges,
}),
diff --git a/apps/desktop/src/renderer/state/pendingFirstMessage.ts b/apps/desktop/src/renderer/state/pendingFirstMessage.ts
index f2f2bd5bce..5ad062de7a 100644
--- a/apps/desktop/src/renderer/state/pendingFirstMessage.ts
+++ b/apps/desktop/src/renderer/state/pendingFirstMessage.ts
@@ -15,6 +15,7 @@
import type { AttachedFile, MentionedResource } from '@/lib/fileTypes';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
+import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
export interface PendingPayload {
text: string;
@@ -22,6 +23,7 @@ export interface PendingPayload {
mentions?: MentionedResource[];
vendorOptions?: Record<string, unknown>;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: PastedTextRange[];
slashCommandRanges?: SlashCommandRange[];
/** 调试用——createPending 时刻,过期清理时可参考(目前未做 GC,实际场景 navigate 立即消费)。 */
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index 059b75c5c1..e779af9e52 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -9,6 +9,12 @@
*/
import { stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';
+import {
+ projectAgentFacingText,
+ type AgentInputReference,
+} from '@cindy/maker-shared/agent-input-projection';
+
+export type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
export type AgentInputFileCategory = 'image' | 'pdf' | 'text' | 'office' | 'file';
@@ -85,6 +91,7 @@ export interface AgentInputChatMessage {
images?: Array<AgentInputImageRef | AgentInputFallbackImage>;
files?: Array<{ name: string; path: string }>;
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
pastedTextRanges?: Array<{ start: number; end: number; display: string }>;
slashCommandRanges?: Array<{ start: number; end: number }>;
}
@@ -128,6 +135,8 @@ export interface AgentInputQueuedMessage {
sessionRefs?: AgentInputSessionRef[];
trustedSessionReferenceContexts?: AgentInputSessionReferenceContext[];
sessionReferencesRequireTrustedSnapshot?: boolean;
+ /** Structured Composer references used only for semantic projection. */
+ agentReferences?: AgentInputReference[];
chatMessage: AgentInputChatMessage;
createOpts: AgentInputCreateOpts;
userName?: string;
@@ -218,12 +227,71 @@ export function queuedMessageRetryToken(queued: AgentInputQueuedMessage): string
export function sanitizeQueuedMessageForPersistence(
item: AgentInputQueuedMessage,
): AgentInputQueuedMessage {
- if (!item.trustedSessionReferenceContexts) return item;
+ let changed = false;
+ let persistedContent = item.persistedContent;
+ let agentReferences = item.agentReferences;
+
+ const stripMessageBodies = (
+ references: readonly unknown[],
+ ): { references: unknown[]; stripped: boolean } => {
+ let stripped = false;
+ const next = references.map((reference) => {
+ if (!reference || typeof reference !== 'object' || Array.isArray(reference)) {
+ return reference;
+ }
+ const record = reference as Record<string, unknown>;
+ if (
+ record.kind !== 'message'
+ || (!Object.hasOwn(record, 'text') && !Object.hasOwn(record, 'truncated'))
+ ) {
+ return reference;
+ }
+ stripped = true;
+ const sanitized = { ...record };
+ delete sanitized.text;
+ delete sanitized.truncated;
+ return sanitized;
+ });
+ return { references: stripped ? next : [...references], stripped };
+ };
+
+ if (agentReferences) {
+ const topLevel = stripMessageBodies(agentReferences);
+ if (topLevel.stripped) {
+ changed = true;
+ agentReferences = topLevel.references as AgentInputReference[];
+ }
+ }
+ try {
+ const parsed = JSON.parse(persistedContent) as unknown;
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ const record = parsed as Record<string, unknown>;
+ if (Array.isArray(record.agentReferences)) {
+ const persisted = stripMessageBodies(record.agentReferences);
+ if (persisted.stripped) {
+ changed = true;
+ persistedContent = JSON.stringify({
+ ...record,
+ agentReferences: persisted.references,
+ });
+ }
+ }
+ }
+ } catch {
+ // Historical plain-text queue payloads have no embedded reference bodies.
+ }
+
+ if (!changed && !item.trustedSessionReferenceContexts) return item;
const sanitized: AgentInputQueuedMessage = {
...item,
- sessionReferencesRequireTrustedSnapshot: true,
+ persistedContent,
+ ...(agentReferences ? { agentReferences } : {}),
+ ...(item.trustedSessionReferenceContexts
+ ? { sessionReferencesRequireTrustedSnapshot: true }
+ : {}),
};
- delete sanitized.trustedSessionReferenceContexts;
+ if (!item.agentReferences) delete sanitized.agentReferences;
+ if (item.trustedSessionReferenceContexts) delete sanitized.trustedSessionReferenceContexts;
return sanitized;
}
@@ -265,6 +333,7 @@ export function updateQueuedMessageText(
// Arbitrary text edits invalidate presentation offsets. A composer-based
// queue edit supplies freshly computed metadata through update-content.
delete nextParsed.pastedTextRanges;
+ delete nextParsed.agentReferences;
// Preserve the explicit "new renderer metadata" marker while clearing
// stale offsets. The empty array prevents legacy line-start guessing.
nextParsed.slashCommandRanges = [];
@@ -297,6 +366,7 @@ export function updateQueuedMessageText(
}
if (sessionRefs.length > 0) updated.sessionRefs = sessionRefs;
else delete updated.sessionRefs;
+ delete updated.agentReferences;
return updated;
}
@@ -326,6 +396,14 @@ export function updateQueuedMessageContent(
// (手机编辑器能完整表达附件,undefined / 空数组都表示清空)。
if (next.files && next.files.length > 0) merged.files = next.files;
else delete merged.files;
+ // Structured references are tied to offsets in the replacement text.
+ // `next` is the complete composer submission, so stale references from the
+ // old queue item must never survive an edit that removed or reordered chips.
+ if (next.agentReferences && next.agentReferences.length > 0) {
+ merged.agentReferences = next.agentReferences;
+ } else {
+ delete merged.agentReferences;
+ }
// mentions 语义不同:手机端编辑器(update-content 目前唯一调用方)不能表达
// mentions,构造的 next 恒不带该字段——undefined 视为「无表达,保留原条目」,
// 只有显式数组才是权威替换(空数组 = 清空)。否则手机编辑一条桌面排队的
@@ -417,13 +495,23 @@ export function serializeSessionReferencePayload(
});
}
+/** Immutable semantic projection shared by Ghost, titles, turn and steer. */
+export function getAgentFacingText(queued: AgentInputQueuedMessage): string {
+ return projectAgentFacingText({
+ text: queued.text,
+ quotesEncoded: queued.chatMessage.quotesEncoded === true,
+ agentReferences: queued.agentReferences,
+ });
+}
+
export function buildMakerUserMessage(
queued: AgentInputQueuedMessage,
sessionReferenceContexts: AgentInputSessionReferenceContext[] = [],
): AgentInputMakerMessage {
const blocks: Array<{ type: string; [k: string]: unknown }> = [];
- if (queued.text.length > 0) {
- blocks.push({ type: 'text', text: queued.text });
+ const agentFacingText = getAgentFacingText(queued);
+ if (agentFacingText.length > 0) {
+ blocks.push({ type: 'text', text: agentFacingText });
}
for (const m of queued.mentions ?? []) {
blocks.push({ type: 'mention', name: m.name, path: m.path, kind: m.type });
diff --git a/apps/mobile/app.json b/apps/mobile/app.json
index 8f0150be13..05adfdc99d 100644
--- a/apps/mobile/app.json
+++ b/apps/mobile/app.json
@@ -54,6 +54,14 @@
"./plugins/with-google-signin-modular-headers",
"./plugins/with-wechat-opensdk-modulemap",
"./plugins/with-android-splash-no-icon",
+ [
+ "expo-build-properties",
+ {
+ "ios": {
+ "buildReactNativeFromSource": true
+ }
+ }
+ ],
[
"expo-splash-screen",
{
diff --git a/apps/mobile/app/files/[sessionId].tsx b/apps/mobile/app/files/[sessionId].tsx
index c20c84510a..e36d4c6591 100644
--- a/apps/mobile/app/files/[sessionId].tsx
+++ b/apps/mobile/app/files/[sessionId].tsx
@@ -417,7 +417,11 @@ export default function RemoteFileBrowserScreen() {
queueComposerAttachment(sessionId, attachment);
router.navigate({
pathname: '/sessions/[sessionId]',
- params: { sessionId, deviceId },
+ params: {
+ sessionId,
+ deviceId,
+ focusComposerRequestKey: String(Date.now()),
+ },
});
return;
}
@@ -425,7 +429,12 @@ export default function RemoteFileBrowserScreen() {
const merged = mergePathIntoComposerDraft(sessionId, item.relPath, item.kind);
router.navigate({
pathname: '/sessions/[sessionId]',
- params: { sessionId, deviceId, draft: merged },
+ params: {
+ sessionId,
+ deviceId,
+ draft: merged,
+ focusComposerRequestKey: String(Date.now()),
+ },
});
}, [absolutePathOf, deviceId, router, sessionId]);
@@ -518,7 +527,11 @@ export default function RemoteFileBrowserScreen() {
setLightbox(null);
router.navigate({
pathname: '/sessions/[sessionId]',
- params: { sessionId, deviceId },
+ params: {
+ sessionId,
+ deviceId,
+ focusComposerRequestKey: String(Date.now()),
+ },
});
},
}), [deviceId, router, sessionId]);
@@ -535,7 +548,12 @@ export default function RemoteFileBrowserScreen() {
const merged = mergePathIntoComposerDraft(sessionId, relPath, 'dir');
router.navigate({
pathname: '/sessions/[sessionId]',
- params: { sessionId, deviceId, draft: merged },
+ params: {
+ sessionId,
+ deviceId,
+ draft: merged,
+ focusComposerRequestKey: String(Date.now()),
+ },
});
}, [deviceId, relPath, router, sessionId]);
diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsx
index 5f93be72a2..adbbfa95de 100644
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@ -294,7 +294,12 @@ export default function RemoteFilePreviewScreen() {
const merged = mergePathIntoComposerDraft(sessionId, item.relPath);
router.navigate({
pathname: '/sessions/[sessionId]',
- params: { sessionId, deviceId, draft: merged },
+ params: {
+ sessionId,
+ deviceId,
+ draft: merged,
+ focusComposerRequestKey: String(Date.now()),
+ },
});
}, [deviceId, router, sessionId]);
@@ -371,7 +376,11 @@ export default function RemoteFilePreviewScreen() {
});
router.navigate({
pathname: '/sessions/[sessionId]',
- params: { sessionId, deviceId },
+ params: {
+ sessionId,
+ deviceId,
+ focusComposerRequestKey: String(Date.now()),
+ },
});
}}
readTextFile={readTextFile}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 17c3b7788b..20ce197639 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -74,10 +74,12 @@ import { agentAuthGateHint, agentAuthGateVerdict } from '@/session/agentAuthGate
import { isTransientRemoteError, withTransientRemoteRetry } from '@/device-link/remoteRetry';
import { useRemoteSyncTask } from '@/device-link/remoteSyncTask';
import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';
+import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';
import { useObserve } from '@/observability/observe';
import { InteractionPanel, type MobilePlanViewerState } from '@/session/InteractionPanel';
import { MessageRenderer, type MobileMessageDraft } from '@/session/MessageRenderer';
+import { ComposerRichInput, type ComposerRichInputHandle } from '@/session/ComposerRichInput';
import { InlineQueueSection } from '@/session/InlineQueueSection';
import { RewindPreviewPanel } from '@/session/RewindPreviewPanel';
import { BlurBackdrop } from '@/session/BlurBackdrop';
@@ -160,20 +162,45 @@ import {
detectComposerTrigger,
filterAtResources,
filterSlashCommands,
- insertAtResource,
- insertSlashCommand,
mergeSlashCommands,
} from '@/session/composerPalette';
import { buildComposerTouchLayout } from '@/session/composerTouchLayout';
-import { flushComposerDraftWrites, readComposerDraft, readComposerDraftSync, saveComposerDraft } from '@/session/composerDraftStore';
+import {
+ flushComposerDraftWrites,
+ readComposerDocumentDraft,
+ readComposerDocumentDraftSync,
+ readComposerDraft,
+ readComposerDraftSync,
+ saveComposerDocumentDraft,
+ saveComposerDraft,
+} from '@/session/composerDraftStore';
+import {
+ appendComposerNode,
+ composerDocumentsEqual,
+ composerDocumentHasContent,
+ composerDocumentFromEncodedMessage,
+ composerDocumentProjectedText,
+ composerDocumentQuotes,
+ emptyComposerDocument,
+ hydrateComposerMessageReferenceBodies,
+ mentionComposerNode,
+ migrateLegacyComposerDraft,
+ normalizeComposerDocument,
+ reconcileComposerProjectedText,
+ replaceComposerTextRange,
+ serializeComposerDocument,
+ sessionLinkComposerNode,
+ slashCommandTextNode,
+ textComposerDocument,
+ type ComposerDocument,
+} from '@/session/composerDocument';
+import { boundAgentReferenceText } from '@cindy/maker-shared/agent-input-projection';
import {
appendQuote,
clearQuotes,
getQuotes,
hydrateQuotes,
resolveOrderedQuoteDraft,
- setOrderedQuoteDraft,
- setQuotes,
truncateQuoteText,
useSessionQuotes,
} from '@/session/chatQuoteStore';
@@ -334,6 +361,7 @@ import {
prepareMobileQueuedSessionReferences,
prepareMobileQueuedSessionReferencesForSteer,
} from '@/session/sessionReferences';
+import { compactSessionMessageLabel, mobileSessionMessageDisplayText } from '@/session/sessionMessageText';
import { copyMessageText } from '@/session/messageActions';
import {
remoteSessionStore,
@@ -455,6 +483,7 @@ const TAIL_RETRY_HIDE_TIMEOUT_MS = 15_000;
interface QueueEditingState {
clientId: string;
stashedDraft: string;
+ stashedDocument: ComposerDocument;
stashedAttachments: RemoteSerializedAttachment[];
textState: QueueEditTextState;
}
@@ -536,21 +565,22 @@ function restoreOutboxItemsToDraft(items: readonly MobileOutboxItem[]): void {
existingVisibleText,
existingQuotes,
);
- const existingEncodedBody = existingOrderedDraft?.encodedBody
- ?? formatQuotesForSend(existingQuotes, existingVisibleText);
+ const existingDocument = readComposerDocumentDraftSync(draftSessionId)
+ ?? migrateLegacyComposerDraft(existingVisibleText, existingQuotes, existingOrderedDraft?.encodedBody);
+ const existingEncodedBody = serializeComposerDocument(existingDocument).text;
const recovery = recoverOutboxItemsToComposerDraft(sessionItems, {
visibleText: existingVisibleText,
encodedBody: existingEncodedBody,
quotes: existingQuotes,
+ document: existingDocument,
});
if (recovery.visibleText || recovery.quotes.length > 0) {
saveComposerDraft(draftSessionId, recovery.visibleText);
- }
- if (recovery.quotes.length > 0) {
- setOrderedQuoteDraft(draftSessionId, recovery.quotes, {
- encodedBody: recovery.encodedBody,
- projectedText: recovery.visibleText,
- });
+ saveComposerDocumentDraft(
+ draftSessionId,
+ recovery.document,
+ );
+ clearQuotes(draftSessionId);
}
}
}
@@ -564,6 +594,7 @@ export default function SessionScreen() {
deviceName?: string;
draft?: string;
focusClientId?: string;
+ focusComposerRequestKey?: string;
focusRequestKey?: string;
visualFocusComposer?: string;
visualOpenSearch?: string;
@@ -580,6 +611,7 @@ export default function SessionScreen() {
const deviceName = readRouteParam(params.deviceName) ?? deviceId;
const routeDraft = readRouteParam(params.draft);
const routeFocusClientId = readRouteParam(params.focusClientId);
+ const routeFocusComposerRequestKey = readRouteParam(params.focusComposerRequestKey);
const routeFocusRequestKey = readRouteParam(params.focusRequestKey);
const visualFocusComposer = MOBILE_VISUAL_MOCK_ENABLED && readRouteParam(params.visualFocusComposer) === '1';
const visualOpenSearch = MOBILE_VISUAL_MOCK_ENABLED && readRouteParam(params.visualOpenSearch) === '1';
@@ -615,17 +647,17 @@ export default function SessionScreen() {
if (messages.length > 0) markInteractive();
}, [messages.length, markInteractive]);
const [draft, setDraft] = useState('');
+ const [composerDocument, setComposerDocumentState] = useState<ComposerDocument>(emptyComposerDocument);
+ const [composerDraftHydrated, setComposerDraftHydrated] = useState(false);
// chat-text-quote:待随下一条消息发送的选中文字引用(全局 store,消息流选区
// 按钮 / 文件预览页写入;发送时拼进正文,命中本地命令时保留)。
const quotes = useSessionQuotes(sessionId);
- useEffect(() => {
- if (sessionId) void hydrateQuotes(sessionId);
- }, [sessionId]);
// 采集回调必须 memoize:内联箭头每次渲染换新引用,会让 MessageRenderer 的
// SelectionQuoteContext value 重建,FlatList 里所有可见 MarkdownSelectableText
// 跟着重渲(打字等无关 state 变化都触发),长转录会话开销明显(review P2)。
const handleQuoteSelection = useCallback((quote: { text: string }) => {
appendQuote(sessionId, { text: truncateQuoteText(quote.text) });
+ requestAnimationFrame(() => composerInputRef.current?.focus());
}, [sessionId]);
const [composerFocused, setComposerFocused] = useState(false);
const [composerInputContentHeight, setComposerInputContentHeight] = useState(COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT);
@@ -706,7 +738,10 @@ export default function SessionScreen() {
if (uploadLocalId && routeUploadToOutboxRef.current(uploadLocalId, { failed: true })) return;
setAttachmentError(message);
},
- onPicked: () => setContextSheetOpen(false),
+ onPicked: () => {
+ setContextSheetOpen(false);
+ requestAnimationFrame(() => composerInputRef.current?.focus());
+ },
});
// 换会话与退屏的 outbox 回收:未派发条目的文字合并回草稿库(用户已「发出」的文字
// 不能静默蒸发,回来时出现在输入框里),在途上传任务丢弃(与托盘退出语义一致,
@@ -912,6 +947,7 @@ export default function SessionScreen() {
}
const appliedRouteDraftRef = useRef<string | null>(null);
const draftRef = useRef('');
+ const composerDocumentRef = useRef<ComposerDocument>(emptyComposerDocument());
// 远程媒体取件队列:屏实例级缓存 + 同 url 去重 + 并发上限(每次取件都让桌面端
// 真实上传一次 OSS,列表缩略图懒取件后必须收敛)。deps 经 ref 透传保持队列实例稳定;
// 队列生命周期 = 单个会话:切 sessionId / 退屏时 releaseAll + 补删 + 换新实例
@@ -1051,13 +1087,16 @@ export default function SessionScreen() {
const voiceSuppressNextPressRef = useRef(false);
const voiceStopAfterStartRef = useRef(false);
const finishVoiceRecordingRef = useRef<(() => void) | null>(null);
- const composerInputRef = useRef<NativeTextInput>(null);
+ const composerInputRef = useRef<ComposerRichInputHandle | null>(null);
const composerScrollViewRef = useRef<ScrollView>(null);
const composerScrollEnabledRef = useRef(false);
const voiceDraftScrollRef = useRef<ScrollView>(null);
const voiceControllerSessionRef = useRef<MobileVoiceControllerSession | null>(null);
const voiceDictionaryLearningTrackerRef = useRef<MobileVoiceDictionaryLearningTracker | null>(null);
- const sendLatestRef = useRef<((options?: { draftOverride?: string }) => Promise<void>) | null>(null);
+ const sendLatestRef = useRef<((options?: {
+ draftOverride?: string;
+ documentOverride?: ComposerDocument;
+ }) => Promise<void>) | null>(null);
const sendButtonRef = useRef<View>(null);
const sendButtonFrameRef = useRef<{ height: number; width: number; x: number; y: number } | null>(null);
const slashLoadSeqRef = useRef(0);
@@ -1075,6 +1114,7 @@ export default function SessionScreen() {
const autoRetrySyncKeyRef = useRef<string | null>(null);
const loadedRouteFocusKeyRef = useRef<string | null>(null);
const appliedRouteFocusKeyRef = useRef<string | null>(null);
+ const appliedRouteComposerFocusKeyRef = useRef<string | null>(null);
const targetAvailableRef = useRef<boolean | null>(null);
// 记录已为哪个连接 epoch 触发过 resync;初值 = 首渲染时的 epoch,使首开由 mount effect 单独负责,
// 这个 epoch effect 只在真正重连(epoch 变化)时再同步,避免首开连环重 sync 导致列表重排跳动。
@@ -1483,10 +1523,9 @@ export default function SessionScreen() {
: composerRuntimeSummary.modelSummary
: '';
const composerSendUnavailableReason = canUseComposer ? null : sessionOperationLayout.composerDisabledReason;
- // chat-text-quote:排队编辑是「替换原条目内容」语义,send() 不消费引用
- // (quotesAtSend 置空);布局的可发送判定必须与发送路径一致,否则纯引用 +
- // 空文本时「保存修改」按钮亮着、点了却被空 payload 守卫拦下什么都不发生。
- const composerQuoteCount = queueEditing ? 0 : quotes.length;
+ // 引用已是 ComposerDocument 内的 atom;排队编辑同样可能只有引用而没有可见
+ // 文本,因此必须计入 payload,否则「保存修改」会被错误禁用。
+ const composerQuoteCount = composerDocumentQuotes(composerDocument).length;
// Context 面板是 Modal sheet,不再有内联附件面板 → attachmentPickerOpen 恒 false。
const composerLayout = useMemo(() => buildSessionComposerLayout({
attachmentBusy: false,
@@ -1649,6 +1688,12 @@ export default function SessionScreen() {
Math.abs(currentHeight - nextHeight) < 1 ? currentHeight : nextHeight
));
}, []);
+ const handleComposerRichInputHeight = useCallback((height: number) => {
+ const nextHeight = Math.max(COMPOSER_INPUT_SINGLE_LINE_CONTENT_HEIGHT, Math.ceil(height));
+ setComposerInputContentHeight((currentHeight) => (
+ Math.abs(currentHeight - nextHeight) < 1 ? currentHeight : nextHeight
+ ));
+ }, []);
const handleComposerInputPressIn = useCallback(() => {
if (voiceRecordingActiveRef.current || voiceState === 'listening') {
finishVoiceRecordingRef.current?.();
@@ -1805,13 +1850,37 @@ export default function SessionScreen() {
[bottomOverlayContentHeight],
);
- const applyComposerDraft = useCallback((value: string, options?: { persist?: boolean }) => {
- draftRef.current = value;
- setDraft(value);
- voiceDictionaryLearningTrackerRef.current?.inspectDraft(value);
- if (options?.persist !== false) saveComposerDraft(sessionId, value);
+ const applyComposerDocument = useCallback((
+ value: ComposerDocument,
+ options?: { persist?: boolean },
+ ) => {
+ composerDocumentRef.current = value;
+ setComposerDocumentState(value);
+ const projected = composerDocumentProjectedText(value);
+ draftRef.current = projected;
+ setDraft(projected);
+ voiceDictionaryLearningTrackerRef.current?.inspectDraft(projected);
+ if (options?.persist !== false) {
+ saveComposerDocumentDraft(sessionId, value);
+ // Keep the legacy string mirror during the one-way migration window so
+ // older builds do not turn a rich draft into an empty composer.
+ saveComposerDraft(sessionId, projected);
+ }
}, [sessionId]);
+ const applyComposerDraft = useCallback((value: string, options?: { persist?: boolean }) => {
+ const document = reconcileComposerProjectedText(composerDocumentRef.current, value);
+ applyComposerDocument(document, options);
+ }, [applyComposerDocument]);
+
+ const replaceComposerDraft = useCallback((value: string, options?: { persist?: boolean }) => {
+ applyComposerDocument(textComposerDocument(value), options);
+ }, [applyComposerDocument]);
+
+ const applyRichComposerChange = useCallback((value: ComposerDocument) => {
+ applyComposerDocument(value, queueEditingRef.current ? { persist: false } : undefined);
+ }, [applyComposerDocument]);
+
const setComposerDraft = useCallback((next: SetStateAction<string>) => {
const value = typeof next === 'function' ? next(draftRef.current) : next;
// 排队编辑模式下 composer 内容是临时编辑文本,一律不写草稿库(对所有调用方
@@ -1822,19 +1891,18 @@ export default function SessionScreen() {
applyComposerDraft(value, queueEditingRef.current ? { persist: false } : undefined);
}, [applyComposerDraft]);
- const restoreComposerDraft = useCallback((value: string) => {
- applyComposerDraft(value, { persist: false });
- }, [applyComposerDraft]);
+ const moveComposerCaretToEnd = useCallback(() => {
+ composerInputRef.current?.setSelectionToEnd();
+ }, []);
useEffect(() => {
if (!voiceIsListening) return undefined;
const frame = requestAnimationFrame(() => {
- const end = draftRef.current.length;
- composerInputRef.current?.setNativeProps({ selection: { start: end, end } });
+ moveComposerCaretToEnd();
voiceDraftScrollRef.current?.scrollToEnd({ animated: false });
});
return () => cancelAnimationFrame(frame);
- }, [composerInputContentHeight, composerInputVisibleHeight, draft, voiceIsListening]);
+ }, [composerInputContentHeight, composerInputVisibleHeight, draft, moveComposerCaretToEnd, voiceIsListening]);
useEffect(() => {
if (voiceIsListening && draft.length > 0) return;
@@ -1957,21 +2025,88 @@ export default function SessionScreen() {
const key = `${sessionId}:${routeDraft ?? ''}`;
if (appliedRouteDraftRef.current === key) return;
appliedRouteDraftRef.current = key;
+ setComposerDraftHydrated(false);
let cancelled = false;
const immediateDraft = readComposerDraftSync(sessionId) ?? routeDraft ?? '';
- restoreComposerDraft(immediateDraft);
- void readComposerDraft(sessionId).then((storedDraft) => {
+ const immediateQuotes = getQuotes(sessionId);
+ const immediateOrdered = resolveOrderedQuoteDraft(sessionId, immediateDraft, immediateQuotes);
+ const immediateStoredDocument = readComposerDocumentDraftSync(sessionId);
+ let immediateDocument = immediateStoredDocument
+ ?? migrateLegacyComposerDraft(immediateDraft, immediateQuotes, immediateOrdered?.encodedBody);
+ if (immediateStoredDocument) {
+ for (const quote of immediateQuotes) {
+ immediateDocument = appendComposerNode(immediateDocument, { type: 'quote', quote });
+ }
+ }
+ applyComposerDocument(immediateDocument, { persist: false });
+ const immediateDocumentSnapshot = immediateDocument;
+ // Synchronously consumed quote-store items are already in the first paint.
+ // Clear them before the async hydration window so a concurrent user edit
+ // cannot append the same quote a second time when Promise.all settles.
+ if (immediateQuotes.length > 0) clearQuotes(sessionId);
+ // Memory is the source of truth once quotes were synchronously consumed.
+ // Skipping storage hydration makes it explicit that hydratedQuotes below
+ // can only contain cold-start quotes or quotes arriving after this point.
+ const quoteHydration = immediateQuotes.length > 0
+ ? Promise.resolve()
+ : hydrateQuotes(sessionId);
+
+ void Promise.all([
+ quoteHydration,
+ readComposerDocumentDraft(sessionId),
+ readComposerDraft(sessionId),
+ ]).then(([, storedDocument, storedDraft]) => {
if (cancelled || appliedRouteDraftRef.current !== key) return;
- if (draftRef.current !== immediateDraft) return;
- const nextDraft = storedDraft ?? routeDraft ?? '';
- restoreComposerDraft(nextDraft);
- if (nextDraft.length > 0) saveComposerDraft(sessionId, nextDraft);
+ const hydratedQuotes = [...getQuotes(sessionId)];
+ const fallbackText = storedDraft ?? routeDraft ?? '';
+ const ordered = resolveOrderedQuoteDraft(sessionId, fallbackText, hydratedQuotes);
+ let nextDocument: ComposerDocument;
+ let hydratedQuotesIncluded = false;
+ if (storedDocument) {
+ nextDocument = storedDocument;
+ for (const quote of immediateQuotes) {
+ nextDocument = appendComposerNode(nextDocument, { type: 'quote', quote });
+ }
+ } else if (immediateQuotes.length > 0) {
+ nextDocument = migrateLegacyComposerDraft(
+ fallbackText,
+ immediateQuotes,
+ immediateOrdered?.encodedBody,
+ );
+ } else {
+ nextDocument = migrateLegacyComposerDraft(fallbackText, hydratedQuotes, ordered?.encodedBody);
+ hydratedQuotesIncluded = true;
+ }
+ if (!hydratedQuotesIncluded) {
+ for (const quote of hydratedQuotes) {
+ nextDocument = appendComposerNode(nextDocument, { type: 'quote', quote });
+ }
+ }
+ // User typing during AsyncStorage hydration wins. Newly arrived quote
+ // inbox items are still appended to that live document before clearing.
+ if (!composerDocumentsEqual(composerDocumentRef.current, immediateDocumentSnapshot)) {
+ nextDocument = composerDocumentRef.current;
+ for (const quote of hydratedQuotes) {
+ nextDocument = appendComposerNode(nextDocument, { type: 'quote', quote });
+ }
+ }
+ clearQuotes(sessionId);
+ applyComposerDocument(nextDocument);
+ setComposerDraftHydrated(true);
});
return () => {
cancelled = true;
void flushComposerDraftWrites(sessionId);
};
- }, [restoreComposerDraft, routeDraft, sessionId]);
+ }, [applyComposerDocument, routeDraft, sessionId]);
+
+ useEffect(() => {
+ if (!composerDraftHydrated || quotes.length === 0) return;
+ let next = composerDocumentRef.current;
+ for (const quote of quotes) next = appendComposerNode(next, { type: 'quote', quote });
+ clearQuotes(sessionId);
+ applyComposerDocument(next, queueEditingRef.current ? { persist: false } : undefined);
+ }, [applyComposerDocument, composerDraftHydrated, quotes, sessionId]);
// 点选意图的有效性跟随草稿前缀与会话:一旦草稿不再以点选的 `/name` 开头
// (清空、整段替换、改名)或切换了会话,点选立即作废——覆盖「清稿/替换后手输
@@ -2572,6 +2707,7 @@ export default function SessionScreen() {
// 栈下层保持挂载,返回不会重新 mount,靠 focus 时机领取信箱。
useFocusEffect(
useCallback(() => {
+ let composerFocusFrame: number | null = null;
const pending = drainComposerAttachments(sessionId);
if (pending.length > 0) {
setAttachments((current) => {
@@ -2618,8 +2754,18 @@ export default function SessionScreen() {
})();
}
}
- return undefined;
- }, [sessionId]),
+ if (
+ canUseComposer
+ && routeFocusComposerRequestKey
+ && appliedRouteComposerFocusKeyRef.current !== routeFocusComposerRequestKey
+ ) {
+ appliedRouteComposerFocusKeyRef.current = routeFocusComposerRequestKey;
+ composerFocusFrame = requestAnimationFrame(() => composerInputRef.current?.focus());
+ }
+ return () => {
+ if (composerFocusFrame !== null) cancelAnimationFrame(composerFocusFrame);
+ };
+ }, [canUseComposer, routeFocusComposerRequestKey, sessionId]),
);
useFocusEffect(
@@ -3091,12 +3237,36 @@ export default function SessionScreen() {
pendingSkillSelectionRef.current = command.kind === 'agent-skill'
? { name: command.name, sid: sessionId }
: null;
- setComposerDraft((current) => insertSlashCommand(current, detectComposerTrigger(current), command));
- }, [sessionId, setComposerDraft]);
+ const trigger = detectComposerTrigger(draftRef.current);
+ if (trigger.kind !== 'slash') return;
+ const nextDocument = replaceComposerTextRange(
+ composerDocumentRef.current,
+ trigger.from,
+ draftRef.current.length,
+ [slashCommandTextNode(command.name), { type: 'text', text: ' ' }],
+ );
+ applyComposerDocument(
+ nextDocument,
+ queueEditingRef.current ? { persist: false } : undefined,
+ );
+ composerInputRef.current?.applyDocumentAndSetSelectionToEnd(nextDocument);
+ }, [applyComposerDocument, sessionId]);
const selectAtResource = useCallback((item: MobileAtResourceItem) => {
- setComposerDraft((current) => insertAtResource(current, detectComposerTrigger(current), item));
- }, [setComposerDraft]);
+ const trigger = detectComposerTrigger(draftRef.current);
+ if (trigger.kind !== 'at') return;
+ const nextDocument = replaceComposerTextRange(
+ composerDocumentRef.current,
+ trigger.from,
+ draftRef.current.length,
+ [mentionComposerNode(item), { type: 'text', text: ' ' }],
+ );
+ applyComposerDocument(
+ nextDocument,
+ queueEditingRef.current ? { persist: false } : undefined,
+ );
+ composerInputRef.current?.applyDocumentAndSetSelectionToEnd(nextDocument);
+ }, [applyComposerDocument]);
const startVoiceRecording = useCallback(async () => {
if (
@@ -3368,19 +3538,24 @@ export default function SessionScreen() {
setVoiceState('submitting');
setVoiceError(null);
try {
+ // stop() can deliver an empty final transcript through onDraftChanged before
+ // resolving. Capture the rich document first so quote/reference atoms survive.
+ const documentBeforeStop = composerDocumentRef.current;
const latestDraft = await controller.stop();
await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
setVoiceState('done');
requestAnimationFrame(() => {
- const end = latestDraft.length;
- composerInputRef.current?.setNativeProps({ selection: { start: end, end } });
+ moveComposerCaretToEnd();
});
// chat-text-quote:纯引用(无转写文字、无附件)也要发出去——发送按钮在
// quote-only 时可见,漏了引用会变成「点发送只停了录音、消息没发」。
- if (options.sendAfterTranscribe && (latestDraft.trim() || attachments.length > 0 || getQuotes(sessionId).length > 0)) {
+ const latestDocument = latestDraft.trim()
+ ? reconcileComposerProjectedText(documentBeforeStop, latestDraft)
+ : documentBeforeStop;
+ if (options.sendAfterTranscribe && (composerDocumentHasContent(latestDocument) || attachments.length > 0)) {
const sendLatest = sendLatestRef.current;
if (!sendLatest) throw new Error('消息发送器未初始化。');
- await sendLatest({ draftOverride: latestDraft });
+ await sendLatest({ documentOverride: latestDocument });
}
} catch (err) {
voiceControllerSessionRef.current = null;
@@ -3391,7 +3566,7 @@ export default function SessionScreen() {
} finally {
voiceStopInFlightRef.current = false;
}
- }, [attachments.length, voiceState]);
+ }, [attachments.length, moveComposerCaretToEnd, voiceState]);
const openVoiceSettings = useCallback(() => {
void Linking.openSettings().catch((err) => {
@@ -3627,6 +3802,9 @@ export default function SessionScreen() {
...buildQueuedTextMessage(sessionAtSend, item.text, new Date(), item.clientId, {
attachments: outboxItemAttachments(item),
quotesEncoded: item.quotesEncoded,
+ agentReferences: item.agentReferences,
+ pastedTextRanges: item.pastedTextRanges,
+ slashCommandRanges: item.slashCommandRanges,
}),
...(item.sessionRefs && item.sessionRefs.length > 0
? { sessionRefs: [...item.sessionRefs] }
@@ -3752,70 +3930,115 @@ export default function SessionScreen() {
const outboxDisplayItems = useMemo(() => outboxItems.map(outboxDisplayItem), [outboxItems]);
- async function send(options: { draftOverride?: string } = {}) {
- if (voiceState === 'listening' && options.draftOverride === undefined) {
+ async function send(options: {
+ draftOverride?: string;
+ documentOverride?: ComposerDocument;
+ } = {}) {
+ if (
+ voiceState === 'listening' &&
+ options.draftOverride === undefined &&
+ options.documentOverride === undefined
+ ) {
await finishVoiceRecording({ sendAfterTranscribe: true });
return;
}
- const visibleDraft = options.draftOverride ?? draft;
+ const documentAtSend = options.documentOverride
+ ?? (options.draftOverride === undefined
+ ? composerDocumentRef.current
+ : reconcileComposerProjectedText(composerDocumentRef.current, options.draftOverride));
+ const visibleDraft = composerDocumentProjectedText(documentAtSend);
const body = visibleDraft.trim();
+ const serializedAtSend = serializeComposerDocument(documentAtSend);
const queueEditAtSendStart = queueEditingRef.current;
const queueEditSubmission = queueEditAtSendStart
- ? resolveQueueEditTextSubmission(queueEditAtSendStart.textState, visibleDraft)
+ ? resolveQueueEditTextSubmission(queueEditAtSendStart.textState, documentAtSend)
: null;
const queueEditPreservesEncodedQuotes = queueEditSubmission?.quotesEncoded === true;
- // chat-text-quote:排队编辑是「替换原条目内容」语义,不注入引用;正常发送把
- // 引用块前置在正文前(与桌面 ChatInput 的 formatQuotesForSend 对偶)。排队
- // 引用的可见文本未改时无损复用隐藏 marked body;改过就降级为普通 Markdown。
- // 命令判定(下方)用 body,命中命令时引用保留在胶囊里不消费。
- const quotesAtSend = queueEditAtSendStart ? [] : [...getQuotes(sessionId)];
- // fork / rewind 恢复的交错消息带一份隐藏 ordered body。仅当可见正文与引用
- // 列表都完全没变时复用,保证「引用 A → 回复 A → 引用 B → 回复 B」默认
- // 重发不改 prompt 顺序;任一处被编辑就显式失效并安全回落到引用前置格式。
- const orderedDraftAtSend = queueEditAtSendStart
- ? null
- : resolveOrderedQuoteDraft(sessionId, visibleDraft, quotesAtSend);
- const text = queueEditSubmission?.text
- ?? orderedDraftAtSend?.encodedBody
- ?? formatQuotesForSend(quotesAtSend, body);
+ const text = queueEditSubmission?.text ?? serializedAtSend.text;
+ const quotesEncodedAtSend = queueEditSubmission?.quotesEncoded ?? serializedAtSend.quotesEncoded;
+ let agentReferencesAtSend = queueEditSubmission?.agentReferences ?? serializedAtSend.agentReferences;
+ const pastedTextRangesAtSend = queueEditSubmission?.pastedTextRanges ?? serializedAtSend.pastedTextRanges;
+ const slashCommandRangesAtSend = queueEditSubmission?.slashCommandRanges ?? serializedAtSend.slashCommandRanges;
if (!canUseComposer) {
- if (options.draftOverride !== undefined) setComposerDraft(options.draftOverride);
+ if (options.documentOverride) applyComposerDocument(options.documentOverride);
+ else if (options.draftOverride !== undefined) setComposerDraft(options.draftOverride);
+ return;
+ }
+ if (
+ (!text && attachments.length === 0 && pendingUploads.length === 0) ||
+ sendInFlightRef.current ||
+ sending ||
+ !deviceId
+ ) {
+ if (options.documentOverride) applyComposerDocument(options.documentOverride);
return;
}
- if ((!text && attachments.length === 0 && pendingUploads.length === 0) || sendInFlightRef.current || sending || !deviceId) return;
if (!currentSession) {
setError('未找到当前远程会话,请重新同步后再发送。');
+ if (options.documentOverride) applyComposerDocument(options.documentOverride);
return;
}
sendInFlightRef.current = true;
setSending(true);
setError(null);
+ const outboxEligible = !queueEditAtSendStart;
+ const uploadsInFlight = outboxEligible ? getPendingUploadCount() : 0;
+ const willHaveAttachments = attachmentsRef.current.length > 0 || uploadsInFlight > 0;
+ const earlyLocalCommand = willHaveAttachments ? null : parseMobileLocalSystemCommand(body);
+ const pendingSkillAtSend = pendingSkillSelectionRef.current;
+ const parsedDesktopCommandAtSend = willHaveAttachments
+ ? null
+ : parseMobileDesktopCommand(body, slashCommands);
+ const earlyDesktopCommand =
+ parsedDesktopCommandAtSend
+ && pendingSkillAtSend?.sid === sessionId
+ && pendingSkillAtSend.name === parsedDesktopCommandAtSend.name
+ ? null
+ : parsedDesktopCommandAtSend;
+ const sessionRefsAtSend = outboxEligible && !earlyLocalCommand && !earlyDesktopCommand
+ ? extractMobileSessionReferences(text, remoteSessionStore.getSessionDeviceId)
+ : [];
+ pendingSkillSelectionRef.current = null;
// 乐观第一拍:点发送立刻清空输入框并跟到底部,不等任何网络往返(enqueue 是
// device-link 远程调用,弱网下数秒;文字已捕获进 text)。失败时若输入框仍为空
// 则恢复原文——用户可能在 await 期间又打了字,不能覆盖。
- const draftBeforeSend = options.draftOverride ?? draft;
- // chat-text-quote:引用是否已被本次发送消费(乐观第二拍置真)。失败恢复用
- // 标记而非「store 为空」判断——发送等待期间用户可能新采集了引用,不能覆盖。
- let quotesConsumed = false;
+ const documentBeforeSend = documentAtSend;
+ // 本地命令只消费命令文本,不消费不可见的 quote atom。其它消息仍整份离开
+ // composer。排队编辑不走命令分流,保存时按整条临时文档处理。
+ const documentAfterOptimisticClear =
+ outboxEligible && (earlyLocalCommand || earlyDesktopCommand)
+ ? normalizeComposerDocument({
+ version: 1,
+ nodes: documentAtSend.nodes.filter((node) => node.type === 'quote'),
+ })
+ : emptyComposerDocument();
const restoreDraftAfterFailure = () => {
// 走持久化写回(setComposerDraft 而非 restoreComposerDraft):乐观清空那拍已把
// 草稿库删除并打了 cleared 标,只回内存的话 remount 后草稿读到 null、原文丢失
// (codex review R16)。restoreComposerDraft 的 persist:false 语义只适用于
// 「从草稿库读出来回填」的初始化路径。
- if (body && draftRef.current.trim().length === 0) setComposerDraft(draftBeforeSend);
- // 引用与草稿对称恢复:把已消费的快照前置回填(保持原有顺序),等待期间
- // 新采集的引用跟在后面原样保留;标记复位防止多个失败分支重复回填。
- if (quotesConsumed) {
- quotesConsumed = false;
- const restoredQuotes = [...quotesAtSend, ...getQuotes(sessionId)];
- if (orderedDraftAtSend) {
- setOrderedQuoteDraft(sessionId, restoredQuotes, orderedDraftAtSend);
- } else {
- setQuotes(sessionId, restoredQuotes);
- }
+ if (composerDocumentsEqual(composerDocumentRef.current, documentAfterOptimisticClear)) {
+ applyComposerDocument(documentBeforeSend);
}
};
- if (body) setComposerDraft('');
+ if (text) applyComposerDocument(documentAfterOptimisticClear);
+ // A pasted message link is committed to the editor synchronously, while
+ // its readable body is fetched from the source device asynchronously.
+ // The optimistic clear above preserves the existing "tap sends this
+ // snapshot" boundary; await the body on that captured document so a fast
+ // send still carries semantic content without consuming later typing.
+ const hydratedDocumentAtSend = await hydrateComposerMessageReferenceBodies(
+ documentAtSend,
+ resolvePastedSessionLinkLabel,
+ );
+ if (!composerDocumentsEqual(hydratedDocumentAtSend, documentAtSend)) {
+ agentReferencesAtSend = queueEditAtSendStart
+ ? resolveQueueEditTextSubmission(
+ queueEditAtSendStart.textState,
+ hydratedDocumentAtSend,
+ ).agentReferences
+ : serializeComposerDocument(hydratedDocumentAtSend).agentReferences;
+ }
// 排队编辑保存的编辑态快照:下方 waitForPendingUploads 可能耗时数秒,期间用户
// 可能点 × 放弃或切换编辑目标——等待结束后以快照与最新 ref 比对,不一致则中止
// 保存,防止编辑文本被当成一条全新消息发出(PR#709 review P1)。
@@ -3827,17 +4050,10 @@ export default function SessionScreen() {
// 粘贴占位窗口(uploadsInFlight 计入占位数)同样走本分支:先等占位落定再划归,
// 见分支内注释——不豁免,否则占位窗口内的发送会经原路径直接 enqueue 超车
// outbox 在途消息(greptile review P1)。除占位等待外判断与划归全程同步,无竞态窗。
- const outboxEligible = !queueEditAtSendStart;
- const uploadsInFlight = outboxEligible ? getPendingUploadCount() : 0;
- const willHaveAttachments = attachmentsRef.current.length > 0 || uploadsInFlight > 0;
- const earlyLocalCommand = willHaveAttachments ? null : parseMobileLocalSystemCommand(body);
- const sessionRefsAtSend = outboxEligible && !earlyLocalCommand
- ? extractMobileSessionReferences(text, remoteSessionStore.getSessionDeviceId)
- : [];
// outboxPumpBusyRef 也算「outbox 在途」:派发起点条目即移出 outbox,enqueue
// 弱网重试窗内 outbox 可能为空——此时新消息若走原路径会并发 enqueue 超车
// 在途消息,破坏 FIFO(review P1);计入 pump busy 让它同样进 outbox 排队。
- if (outboxEligible && !earlyLocalCommand
+ if (outboxEligible && !earlyLocalCommand && !earlyDesktopCommand
&& (uploadsInFlight > 0 || outboxRef.current.length > 0 || outboxPumpBusyRef.current)) {
try {
if (!currentSession.workingDir) {
@@ -3872,13 +4088,6 @@ export default function SessionScreen() {
setAttachments([]);
attachmentsRef.current = [];
setAttachmentError(null);
- // 引用消费(同原乐观二拍口径,按快照身份精确摘除)。outbox 条目删除 / 失败
- // 不回填——消息与引用都还在气泡里,重试即可,没有「内容蒸发」窗口。
- if (quotesAtSend.length > 0) {
- const pendingConsume = new Set(quotesAtSend);
- const quotesAfterConsume = getQuotes(sessionId).filter((quote) => !pendingConsume.delete(quote));
- setQuotes(sessionId, quotesAfterConsume);
- }
// plan 一次性语义:权限档快照进条目(派发按快照发),chip 立即恢复——
// 不等附件上传完,与「消息已发出」的乐观语义一致。
const permissionModeAtSend = permissionModeOrAsk(currentSession.permissionMode);
@@ -3892,8 +4101,11 @@ export default function SessionScreen() {
clientId: createOutboxClientId(),
sessionId,
text,
- quotesEncoded: quotesAtSend.length > 0,
+ quotesEncoded: quotesEncodedAtSend,
sessionRefs: sessionRefsAtSend,
+ agentReferences: agentReferencesAtSend,
+ pastedTextRanges: pastedTextRangesAtSend,
+ slashCommandRanges: slashCommandRangesAtSend ?? [],
permissionModeAtSend,
readyAttachments,
readyPreviews,
@@ -3946,6 +4158,9 @@ export default function SessionScreen() {
...buildQueuedTextMessage(sessionAtSend, text, new Date(), editingQueueItem.clientId, {
attachments: sendAttachments,
quotesEncoded: queueEditPreservesEncodedQuotes,
+ agentReferences: agentReferencesAtSend,
+ pastedTextRanges: pastedTextRangesAtSend,
+ slashCommandRanges: slashCommandRangesAtSend,
}),
...(original.sessionRefs && original.sessionRefs.length > 0
? { sessionRefs: [...original.sessionRefs] }
@@ -4041,24 +4256,14 @@ export default function SessionScreen() {
return;
}
// 命令判定用 body(不含引用块):带引用时 /context 等本地命令仍生效,且不消费引用。
- const localSystemCommand = hasAttachments ? null : parseMobileLocalSystemCommand(body);
+ const localSystemCommand = hasAttachments ? null : earlyLocalCommand;
// desktop 命令(/learn)按名字白名单分流;同名 agent-skill 优先让行(对齐桌面
// dispatch 语义),清单未加载时白名单兜底拦截。
// slashCommands 在 palette 打开时含已加载清单(同名 skill 让行);palette
// 关闭时被清为[],退回白名单。例外:用户从 palette 点选了 agent-skill
// (pendingSkillSelectionRef 有值)时,即使 slashCommands 已清也应让行——
// 点选意图明确,不应被白名单覆盖。点选后再次打开 palette 或发送后 ref 清零。
- const pendingSkill = pendingSkillSelectionRef.current;
- pendingSkillSelectionRef.current = null;
- const parsedDesktopCommand = hasAttachments ? null : parseMobileDesktopCommand(body, slashCommands);
- // 若用户明确点选了同名 skill(且点选发生在当前会话),优先让行。
- // sid 验证防止跨会话残留:切换会话后 ref 中的旧会话点选不应影响新会话 dispatch。
- const desktopCommand =
- parsedDesktopCommand
- && pendingSkill?.sid === sessionId
- && pendingSkill.name === parsedDesktopCommand.name
- ? null
- : parsedDesktopCommand;
+ const desktopCommand = hasAttachments ? null : earlyDesktopCommand;
if (!sessionAtSend.workingDir && !localSystemCommand && !desktopCommand) {
setError('当前会话缺少工作目录,不能发送消息。');
restoreDraftAfterFailure();
@@ -4126,7 +4331,10 @@ export default function SessionScreen() {
}
const queuedDraft = buildQueuedTextMessage(sessionAtSend, text, new Date(), undefined, {
attachments: sendAttachments,
- quotesEncoded: quotesAtSend.length > 0,
+ quotesEncoded: quotesEncodedAtSend,
+ agentReferences: agentReferencesAtSend,
+ pastedTextRanges: pastedTextRangesAtSend,
+ slashCommandRanges: slashCommandRangesAtSend,
});
let queued: QueuedRemoteMessage;
try {
@@ -4155,21 +4363,6 @@ export default function SessionScreen() {
// 标注再编辑真相(矢量笔迹 + 原图副本)不在乐观段清:enqueue 失败回滚恢复
// 托盘后,标注附件必须还能继续编辑/撤销(review P2);成功收尾按本批精确清。
setAttachmentError(null);
- // 引用消费与附件托盘同拍(乐观第二拍):按快照身份精确摘除(store 的条目
- // 引用稳定),发送等待期间新采集的引用保留——不能整库 clear,否则等待期
- // 加的引用会被误削且失败恢复只回快照、新引用永久丢失(review P1)。
- // quotesConsumed 只在确有快照条目被摘除时才置真:等待期间用户若已点 X
- // 清空引用,store 里已没有快照条目可摘除,此时若仍标记 consumed,发送失败
- // 回滚会把用户刚清空的引用重新塞回输入区(greptile review P1)。
- if (quotesAtSend.length > 0) {
- const pendingConsume = new Set(quotesAtSend);
- const quotesBeforeConsume = getQuotes(sessionId);
- const quotesAfterConsume = quotesBeforeConsume.filter((quote) => !pendingConsume.delete(quote));
- if (quotesAfterConsume.length !== quotesBeforeConsume.length) {
- setQuotes(sessionId, quotesAfterConsume);
- quotesConsumed = true;
- }
- }
requestMessageListFollowLatest();
try {
// 弱网重试:切基站 / 短暂断连时自动补发,不让用户为一次抖动手动重发。
@@ -4611,25 +4804,27 @@ export default function SessionScreen() {
? {
clientId: item.clientId,
stashedDraft: previous.stashedDraft,
+ stashedDocument: previous.stashedDocument,
stashedAttachments: previous.stashedAttachments,
textState,
}
: {
clientId: item.clientId,
stashedDraft: draftRef.current,
+ stashedDocument: composerDocumentRef.current,
stashedAttachments: [...attachmentsRef.current],
textState,
};
queueEditingRef.current = next;
setQueueEditing(next);
setQueueSelectedClientId(null);
- setComposerDraft(textState.visibleText);
+ applyComposerDocument(textState.document, { persist: false });
const files = item.files ? [...item.files] : [];
attachmentsRef.current = files;
setAttachments(files);
setAttachmentError(null);
setQueueEditLock(item.clientId, true);
- composerInputRef.current?.focus();
+ composerInputRef.current?.applyDocumentAndSetSelectionToEnd(textState.document);
};
/** 放弃排队消息编辑:解锁 + 回收编辑期新增附件 + 恢复进入前的草稿与附件托盘。 */
@@ -4644,10 +4839,10 @@ export default function SessionScreen() {
.catch(() => undefined);
}
discardQueueEditTransientAttachments(editing);
- setComposerDraft(editing.stashedDraft);
+ applyComposerDocument(editing.stashedDocument);
attachmentsRef.current = [...editing.stashedAttachments];
setAttachments([...editing.stashedAttachments]);
- }, [applyProjection, discardQueueEditTransientAttachments, maker, sessionId, setComposerDraft]);
+ }, [applyComposerDocument, applyProjection, discardQueueEditTransientAttachments, maker, sessionId]);
// 编辑中的条目从队列消失(被远端发出/删除)→ 原文已不可改,自动退出编辑并恢复
// stash。条目已不存在,无锁可解(unlock: false)。
@@ -5034,6 +5229,7 @@ export default function SessionScreen() {
},
})), { token: auth.getAccessToken() });
setContextSheetOpen(false);
+ requestAnimationFrame(() => composerInputRef.current?.focus());
}, [auth, enqueueUploads, pendingMediaAssets]);
// 勾选态按「映射的附件仍在列表里」现算,附件被单独移除 / 发送清空后角标自动消失。
const selectedMediaAssetIds = useMemo(() => {
@@ -5605,7 +5801,14 @@ export default function SessionScreen() {
target.relPath ?? target.absPath,
target.kind === 'directory' ? 'dir' : 'file',
);
- applyComposerDraft(merged, { persist: false });
+ const mergedDocument = readComposerDocumentDraftSync(sessionId);
+ if (mergedDocument) {
+ applyComposerDocument(mergedDocument, { persist: false });
+ composerInputRef.current?.applyDocumentAndSetSelectionToEnd(mergedDocument);
+ } else {
+ applyComposerDraft(merged, { persist: false });
+ composerInputRef.current?.applyDocumentAndSetSelectionToEnd(composerDocumentRef.current);
+ }
setChipMenuTarget(null);
return;
}
@@ -5618,7 +5821,7 @@ export default function SessionScreen() {
void shareChipFile(target);
return;
}
- }, [applyComposerDraft, deviceId, deviceName, openChatPathTarget, router, sessionId, shareChipFile]);
+ }, [applyComposerDocument, applyComposerDraft, deviceId, deviceName, openChatPathTarget, router, sessionId, shareChipFile]);
// 会话菜单元数据操作(重命名 / 置顶 / 归档 / 删除 / 恢复)乐观写:与首页
// patchHomeSession 同一写序契约——守卫 / 队列 / 在途登记用 app 级单例
@@ -5718,6 +5921,7 @@ export default function SessionScreen() {
clientId,
draftText: draft.text,
draftQuotes: draft.quotes,
+ draftDocument: draft.document,
...(draft.orderedBody ? { draftOrderedBody: draft.orderedBody } : {}),
});
try {
@@ -5731,6 +5935,7 @@ export default function SessionScreen() {
preview,
draft.quotes,
draft.orderedBody,
+ draft.document,
));
} catch (err) {
if (rewindRequestSeqRef.current !== seq) return;
@@ -5739,6 +5944,7 @@ export default function SessionScreen() {
clientId,
draftText: draft.text,
draftQuotes: draft.quotes,
+ draftDocument: draft.document,
...(draft.orderedBody ? { draftOrderedBody: draft.orderedBody } : {}),
errorText: formatRemoteError(err),
});
@@ -5748,22 +5954,21 @@ export default function SessionScreen() {
}
}, [maker, messageActionBusy, sessionId]);
- const forkAtMessage = useCallback(async (clientId: string, draft?: MobileMessageDraft) => {
+ const performForkAtMessage = useCallback(async (clientId: string, draft?: MobileMessageDraft) => {
if (!deviceId || messageActionBusy) return;
setMessageActionBusy(clientId);
setError(null);
try {
const forked = await maker.fork(sessionId, clientId);
remoteSessionStore.upsertDeviceSession(deviceId, deviceName, forked);
- saveComposerDraft(forked.id, draft?.text);
- if (draft?.orderedBody && draft.quotes.length > 0) {
- setOrderedQuoteDraft(forked.id, draft.quotes, {
- encodedBody: draft.orderedBody,
- projectedText: draft.text,
- });
- } else {
- setQuotes(forked.id, draft?.quotes ?? []);
- }
+ const forkDocument = draft?.document ?? migrateLegacyComposerDraft(
+ draft?.text,
+ draft?.quotes ?? [],
+ draft?.orderedBody,
+ );
+ saveComposerDocumentDraft(forked.id, forkDocument);
+ saveComposerDraft(forked.id, composerDocumentProjectedText(forkDocument));
+ clearQuotes(forked.id);
router.push({
pathname: '/sessions/[sessionId]',
params: { sessionId: forked.id, deviceId, deviceName },
@@ -5775,6 +5980,18 @@ export default function SessionScreen() {
}
}, [deviceId, deviceName, maker, messageActionBusy, router, sessionId]);
+ const forkAtMessage = useCallback((clientId: string, draft?: MobileMessageDraft) => {
+ if (!deviceId || messageActionBusy) return;
+ Alert.alert(
+ '从这里开启一个新对话?',
+ '系统会根据这里的对话上下文创建一个独立的新对话。原对话不会改变,之后两边的消息互不影响。',
+ [
+ { text: '取消', style: 'cancel' },
+ { text: '开启新对话', onPress: () => void performForkAtMessage(clientId, draft) },
+ ],
+ );
+ }, [deviceId, messageActionBusy, performForkAtMessage]);
+
const openForkOrigin = useCallback(() => {
const parentSessionId = currentSession?.parentSessionId;
const forkedAtMessageId = currentSession?.forkedAtMessageId;
@@ -5843,6 +6060,80 @@ export default function SessionScreen() {
void copyMessageText(buildMobileSessionMessageDeepLink(sessionId, clientId));
}, [sessionId]);
+ const resolvePastedSessionLinkLabel = useCallback(async (href: string) => {
+ const target = parseSessionDeepLinkUrl(href);
+ if (!target) return null;
+ const targetSession = remoteSessionStore.getSessions().find((item) => (
+ item.id === target.sessionId
+ ));
+ const targetDeviceId = targetSession?.canonicalDeviceId
+ ?? targetSession?.deviceLinkDeviceId
+ ?? remoteSessionStore.getSessionDeviceId(target.sessionId);
+ const targetMaker = targetDeviceId
+ ? (targetDeviceId === deviceId
+ ? maker
+ : createMobileMakerTransport({ deviceId: targetDeviceId, invoke }))
+ : null;
+
+ try {
+ if (target.messageClientId) {
+ let targetMessage = remoteSessionStore.getMessages(target.sessionId).find((message) => (
+ message.clientId === target.messageClientId || message.id === target.messageClientId
+ ));
+ if (!targetMessage && targetMaker && targetDeviceId) {
+ await openLink(targetDeviceId);
+ const around = await targetMaker.aroundMessagesByClientId(
+ target.sessionId,
+ target.messageClientId,
+ { radius: 1 },
+ );
+ remoteSessionStore.mergeMessages(target.sessionId, around);
+ targetMessage = around.find((message) => (
+ message.clientId === target.messageClientId || message.id === target.messageClientId
+ ));
+ }
+ const text = targetMessage ? mobileSessionMessageDisplayText(targetMessage) : null;
+ if (!text) return null;
+ const bounded = boundAgentReferenceText(text);
+ return {
+ label: compactSessionMessageLabel(text),
+ agentText: bounded.text,
+ ...(bounded.truncated ? { agentTextTruncated: true } : {}),
+ };
+ }
+
+ const knownTitle = targetSession?.title?.trim();
+ if (knownTitle) return { label: compactSessionMessageLabel(knownTitle) };
+ if (!targetMaker || !targetDeviceId) return null;
+ await openLink(targetDeviceId);
+ const fresh = await targetMaker.getSession(target.sessionId);
+ const title = fresh.title?.trim();
+ return title ? { label: compactSessionMessageLabel(title) } : null;
+ } catch {
+ return null;
+ }
+ }, [deviceId, invoke, maker, openLink]);
+
+ const addMessageToComposer = useCallback((clientId: string) => {
+ if (!sessionId || !canUseComposer) return;
+ const target = messages.find((message) => (
+ message.clientId === clientId || message.id === clientId
+ ));
+ const summary = target ? mobileSessionMessageDisplayText(target) : null;
+ const bounded = summary ? boundAgentReferenceText(summary) : null;
+ const node = sessionLinkComposerNode({
+ href: buildMobileSessionMessageDeepLink(sessionId, clientId),
+ label: compactSessionMessageLabel(summary ?? clientId),
+ titled: true,
+ ...(bounded?.text ? { agentText: bounded.text } : {}),
+ ...(bounded?.truncated ? { agentTextTruncated: true } : {}),
+ });
+ const editor = composerInputRef.current;
+ if (editor) editor.insertNode(node);
+ else applyComposerDocument(appendComposerNode(composerDocumentRef.current, node));
+ requestAnimationFrame(() => composerInputRef.current?.focus());
+ }, [applyComposerDocument, canUseComposer, messages, sessionId]);
+
const deleteMessage = useCallback((clientId: string) => {
if (!deviceId || messageActionBusy) return;
Alert.alert('删除本条对话?', [
@@ -5851,7 +6142,7 @@ export default function SessionScreen() {
].join(''), [
{ text: '取消', style: 'cancel' },
{
- text: '删除',
+ text: '删除本条对话',
style: 'destructive',
onPress: () => {
void (async () => {
@@ -5909,15 +6200,12 @@ export default function SessionScreen() {
}
return;
}
- setComposerDraft(state.draftText);
- if (state.draftOrderedBody && state.draftQuotes.length > 0) {
- setOrderedQuoteDraft(sessionId, state.draftQuotes, {
- encodedBody: state.draftOrderedBody,
- projectedText: state.draftText,
- });
- } else {
- setQuotes(sessionId, state.draftQuotes);
- }
+ applyComposerDocument(state.draftDocument ?? migrateLegacyComposerDraft(
+ state.draftText,
+ state.draftQuotes,
+ state.draftOrderedBody,
+ ));
+ clearQuotes(sessionId);
setRewindState({ kind: 'idle' });
await syncSession({ replaceMessages: true });
} catch (err) {
@@ -5928,13 +6216,14 @@ export default function SessionScreen() {
clientId: state.clientId,
draftText: state.draftText,
draftQuotes: state.draftQuotes,
+ ...(state.draftDocument ? { draftDocument: state.draftDocument } : {}),
...(state.draftOrderedBody ? { draftOrderedBody: state.draftOrderedBody } : {}),
errorText: formatRemoteError(err),
});
} finally {
if (rewindRequestSeqRef.current === seq) setMessageActionBusy(null);
}
- }, [deviceId, maker, messageActionBusy, rewindState, sessionId, syncSession]);
+ }, [applyComposerDocument, deviceId, maker, messageActionBusy, rewindState, sessionId, syncSession]);
return (
<View style={styles.safeArea} testID="session.screen">
@@ -6278,6 +6567,7 @@ export default function SessionScreen() {
items={renderItems}
loadingEarlier={loadingEarlier}
onCopyMessageLink={copyMessageLink}
+ onAddMessageToComposer={canUseComposer ? addMessageToComposer : undefined}
onDeleteMessage={collaborationReadOnlyReason ? undefined : deleteMessage}
onForkMessage={collaborationReadOnlyReason ? undefined : forkAtMessage}
onLoadEarlier={loadEarlierMessages}
@@ -6285,9 +6575,9 @@ export default function SessionScreen() {
onOpenSessionLink={openSessionLink}
onPreviewRewind={collaborationReadOnlyReason ? undefined : previewRewindAtMessage}
// chat-text-quote:选中消息文字 → 引用进本会话草稿(截断后写
- // chatQuoteStore,composer 胶囊即时刷新)。协同只读态不启用;
+ // chatQuoteStore,composer 胶囊即时刷新)。Composer 不可用态不启用;
// 回调已 memoize,保持 SelectionQuoteContext value 稳定。
- onQuoteSelection={collaborationReadOnlyReason ? undefined : handleQuoteSelection}
+ onQuoteSelection={canUseComposer ? handleQuoteSelection : undefined}
onReadTextFilePreview={maker.fs.readTextFilePreview}
onReleaseRemoteMedia={releaseRemoteMedia}
onResolveRemoteMedia={resolveRemoteMedia}
@@ -6591,18 +6881,6 @@ export default function SessionScreen() {
</Text>
) : null}
- {/* chat-text-quote:「N 处引用」胶囊。放 composerSurface 之外、
- ScrollView 之内——不挂 accessoryAbove(那个插槽仅 cardActive
- 渲染,引用要求未聚焦也可见)。 */}
- {quotes.length > 0 ? (
- <QuoteCapsule
- onClear={() => clearQuotes(sessionId)}
- quotes={quotes}
- testIDPrefix="session.quoteCapsule"
- variant="composer"
- />
- ) : null}
-
<View style={[
styles.composerSurface,
compactComposer && !composerCardActive && styles.composerSurfaceCompact,
@@ -6620,8 +6898,44 @@ export default function SessionScreen() {
floatingVoiceButtonStyle={composerFloatingVoiceButtonStyle}
cursorColor={colors.inputCaret}
inputFrameHeight={composerResize.frameHeight}
+ inputElement={(
+ <ComposerRichInput
+ ref={composerInputRef}
+ accessibilityHint={composerLayout.input.disabledReason ?? undefined}
+ accessibilityLabel="输入远程消息"
+ document={composerDocument}
+ editable={!composerLayout.input.disabled}
+ height={composerInputVisibleHeight}
+ hidden={voiceIsListening}
+ maxHeight={composerResize.inputMaxHeight}
+ onBlur={() => {
+ setComposerFocused(false);
+ setComposerVoiceHoldArmed(false);
+ }}
+ onChangeDocument={applyRichComposerChange}
+ onFocus={() => {
+ setComposerFocused(true);
+ handleComposerInputPressIn();
+ }}
+ onHeightChange={handleComposerRichInputHeight}
+ onPasteImages={(uris) => void addPastedImageAttachments(uris)}
+ onPasteImagesLoading={beginPastePlaceholders}
+ onPasteImagesLoadFailed={failPastePlaceholders}
+ placeholder={voiceIsListening ? '' : composerLayout.input.placeholder}
+ resolveSessionLinkLabel={resolvePastedSessionLinkLabel}
+ testID="session.composerRichInput"
+ theme={{
+ background: colors.chatCodeSurface,
+ border: colors.border,
+ chip: colors.surfaceChip,
+ focus: colors.inputCaret,
+ placeholder: colors.textTertiary,
+ text: colors.textPrimary,
+ textSecondary: colors.textSecondary,
+ }}
+ />
+ )}
inputOverlay={renderComposerInputOverlay()}
- inputRef={composerInputRef}
inputStyle={[styles.sessionComposerInput, voiceIsListening && styles.inputVoiceHidden]}
inputTestID="session.composerInput"
leading={renderComposerCollapsedAttachmentBadge()}
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index 742994bda6..ca63c392db 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -20,6 +20,7 @@
"expo-audio": "^56.0.12",
"expo-auth-session": "^56.0.14",
"expo-blur": "~56.0.3",
+ "expo-build-properties": "~56.0.23",
"expo-clipboard": "^56.0.4",
"expo-constants": "^56.0.18",
"expo-crypto": "^56.0.4",
diff --git a/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts b/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts
index dd92984b27..24764396a4 100644
--- a/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts
+++ b/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts
@@ -21,22 +21,25 @@ describe('mobile cross-device quote wiring', () => {
it('propagates quote metadata through direct and attachment-outbox sends', () => {
const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
- expect(source).toContain('quotesEncoded: quotesAtSend.length > 0');
+ expect(source).toContain('quotesEncoded: quotesEncodedAtSend');
+ expect(source).toContain('pastedTextRanges: pastedTextRangesAtSend');
+ expect(source).toContain('slashCommandRanges: slashCommandRangesAtSend');
expect(source).toContain('quotesEncoded: item.quotesEncoded');
expect(source).toContain('restoreOutboxItemsToDraft([item])');
- expect(source).toContain('setOrderedQuoteDraft(draftSessionId, recovery.quotes');
+ expect(source).toContain('saveComposerDocumentDraft(\n draftSessionId,\n recovery.document,');
expect(source).toContain('createQueueEditTextState(item)');
- expect(source).toContain('resolveQueueEditTextSubmission(queueEditAtSendStart.textState, visibleDraft)');
+ expect(source).toContain('resolveQueueEditTextSubmission(queueEditAtSendStart.textState, documentAtSend)');
+ expect(source).toContain('applyComposerDocument(textState.document, { persist: false })');
expect(source).toContain('quotesEncoded: queueEditPreservesEncodedQuotes');
});
it('restores structured quote drafts for mobile fork and rewind actions', () => {
const source = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
- expect(source).toContain('saveComposerDraft(forked.id, draft?.text);');
- expect(source).toContain('setOrderedQuoteDraft(forked.id, draft.quotes');
- expect(source).toContain('setOrderedQuoteDraft(sessionId, state.draftQuotes');
- expect(source).toContain('resolveOrderedQuoteDraft(sessionId, visibleDraft, quotesAtSend)');
+ expect(source).toContain('const forkDocument = draft?.document ?? migrateLegacyComposerDraft(');
+ expect(source).toContain('saveComposerDocumentDraft(forked.id, forkDocument);');
+ expect(source).toContain('applyComposerDocument(state.draftDocument ?? migrateLegacyComposerDraft(');
+ expect(source).toContain('serializeComposerDocument(documentAtSend)');
});
it('strips private markers from queued and outbox raw-text bubbles', () => {
diff --git a/apps/mobile/src/__tests__/composerDocument.test.ts b/apps/mobile/src/__tests__/composerDocument.test.ts
new file mode 100644
index 0000000000..24ae6346b8
--- /dev/null
+++ b/apps/mobile/src/__tests__/composerDocument.test.ts
@@ -0,0 +1,260 @@
+import { describe, expect, it } from 'vitest';
+import { formatQuoteForSend } from '@cindy/maker-shared/chat-quotes';
+import {
+ appendComposerNode,
+ composerDocumentFromEncodedMessage,
+ composerDocumentFromSerializedMessage,
+ composerDocumentProjectedText,
+ hydrateComposerMessageReferenceBodies,
+ isLongComposerPaste,
+ mentionComposerNode,
+ MOBILE_LONG_PASTE_MAX_CHARS,
+ migrateLegacyComposerDraft,
+ pastedTextComposerNode,
+ parseStoredComposerDocument,
+ reconcileComposerProjectedText,
+ removeComposerNode,
+ replaceComposerTextRange,
+ serializeComposerDocument,
+ sessionLinkComposerNode,
+ slashCommandTextNode,
+ textComposerDocument,
+} from '@/session/composerDocument';
+
+describe('mobile composer document', () => {
+ it('roundtrips interleaved quote and text nodes without leaking private markers', () => {
+ const quoteA = { text: 'alpha' };
+ const quoteB = { text: 'beta', sourcePath: 'src/b.ts', startLine: 4, endLine: 5 };
+ const encoded = `${formatQuoteForSend(quoteA)}\n\nreply a\n\n${formatQuoteForSend(quoteB)}\n\nreply b`;
+ const document = composerDocumentFromEncodedMessage(encoded);
+
+ expect(document.nodes.map((node) => node.type)).toEqual(['quote', 'text', 'quote', 'text']);
+ expect(composerDocumentProjectedText(document)).toBe('reply areply b');
+ expect(serializeComposerDocument(document)).toMatchObject({ text: encoded, quotesEncoded: true });
+ });
+
+ it('migrates legacy quotes before the plain text draft', () => {
+ const migrated = migrateLegacyComposerDraft('answer', [{ text: 'quoted' }]);
+ expect(migrated.nodes.map((node) => node.type)).toEqual(['quote', 'text']);
+ expect(serializeComposerDocument(migrated).text).toBe(
+ `${formatQuoteForSend({ text: 'quoted' })}\n\nanswer`,
+ );
+ });
+
+ it('keeps mentions and message links atomic while serializing desktop-compatible text', () => {
+ let document = textComposerDocument('read ');
+ document = appendComposerNode(document, mentionComposerNode({
+ type: 'file',
+ name: 'design notes.md',
+ relPath: 'docs/design notes.md',
+ }));
+ document = appendComposerNode(document, { type: 'text', text: ' then ' });
+ document = appendComposerNode(document, sessionLinkComposerNode({
+ href: 'cindy://session/s-1?message=m-2',
+ label: 'the target message',
+ titled: true,
+ }));
+
+ expect(serializeComposerDocument(document).text).toBe(
+ 'read @"docs/design notes.md" then cindy://session/s-1?message=m-2',
+ );
+ expect(removeComposerNode(document, 1).nodes.map((node) => node.type)).toEqual([
+ 'text', 'session-link',
+ ]);
+ expect(mentionComposerNode({ type: 'file', relPath: 'docs/fallback.md' }).label).toBe(
+ 'docs/fallback.md',
+ );
+ });
+
+ it('awaits missing message-chip bodies before send serialization', async () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const document = {
+ version: 1 as const,
+ nodes: [
+ { type: 'text' as const, text: 'inspect ' },
+ sessionLinkComposerNode({ href, label: 'message-a' }),
+ ],
+ };
+
+ const hydrated = await hydrateComposerMessageReferenceBodies(
+ document,
+ async () => ({
+ label: 'Target message',
+ agentText: 'Complete target body',
+ }),
+ );
+
+ expect(serializeComposerDocument(hydrated).agentReferences).toEqual([
+ expect.objectContaining({
+ kind: 'message',
+ href,
+ text: 'Complete target body',
+ }),
+ ]);
+ expect(document.nodes[1]).not.toHaveProperty('agentText');
+ });
+
+ it('tracks slash decorations as editable text ranges and invalidates them after edits', () => {
+ const document = {
+ version: 1 as const,
+ nodes: [slashCommandTextNode('compact'), { type: 'text' as const, text: ' now' }],
+ };
+ const serialized = serializeComposerDocument(document);
+ expect(serialized.slashCommandRanges).toEqual([{ start: 0, end: 8 }]);
+ expect(serialized.text.slice(0, 8)).toBe('/compact');
+
+ const edited = replaceComposerTextRange(document, 7, 8, [{ type: 'text', text: 'x' }]);
+ expect(serializeComposerDocument(edited).slashCommandRanges).toEqual([]);
+ expect(serializeComposerDocument(edited).text).toBe('/compacx now');
+ });
+
+ it('serializes long paste atoms with exact presentation ranges', () => {
+ let document = textComposerDocument('before ');
+ document = appendComposerNode(document, pastedTextComposerNode('first\nsecond'));
+ document = appendComposerNode(document, { type: 'text', text: ' after' });
+ const serialized = serializeComposerDocument(document);
+ expect(serialized.text).toBe('before first\nsecond after');
+ expect(serialized.pastedTextRanges).toEqual([{
+ start: 7,
+ end: 19,
+ display: 'Pasted text (2 lines)',
+ }]);
+ expect(isLongComposerPaste(Array(24).fill('line').join('\n'))).toBe(true);
+ expect(isLongComposerPaste('x'.repeat(MOBILE_LONG_PASTE_MAX_CHARS + 1))).toBe(true);
+ expect(isLongComposerPaste('short')).toBe(false);
+ });
+
+ it('restores quote, pasted-text and slash metadata into one document', () => {
+ const quote = formatQuoteForSend({ text: 'quoted' });
+ const encoded = `/help before\n\n${quote}\n\nlong\ntext after`;
+ const pasteStart = encoded.indexOf('long\ntext');
+ const restored = composerDocumentFromSerializedMessage(encoded, {
+ quotesEncoded: true,
+ pastedTextRanges: [{
+ start: pasteStart,
+ end: pasteStart + 9,
+ display: 'Pasted text (2 lines)',
+ }],
+ slashCommandRanges: [{ start: 0, end: 5 }],
+ });
+
+ expect(restored.nodes.map((node) => node.type)).toEqual([
+ 'text', 'text', 'quote', 'pasted-text', 'text',
+ ]);
+ expect(serializeComposerDocument(restored)).toEqual({
+ text: encoded,
+ quotesEncoded: true,
+ agentReferences: [],
+ pastedTextRanges: [{
+ start: pasteStart,
+ end: pasteStart + 9,
+ display: 'Pasted text (2 lines)',
+ }],
+ slashCommandRanges: [{ start: 0, end: 5 }],
+ });
+ });
+
+ it('roundtrips message, conversation and project references while keeping deep-link wire text', () => {
+ const messageHref = 'cindy://session/session-a?message=message-a';
+ const sessionHref = 'cindy://session/session-b';
+ const projectHref = 'cindy://project/%2Frepos%2Fcindy';
+ const fullMessage = `Target body ${'x'.repeat(300)}`;
+ const document = {
+ version: 1 as const,
+ nodes: [
+ { type: 'text' as const, text: 'inspect ' },
+ sessionLinkComposerNode({
+ href: messageHref,
+ label: 'compact label',
+ agentText: fullMessage,
+ }),
+ { type: 'text' as const, text: ' continue ' },
+ sessionLinkComposerNode({
+ href: sessionHref,
+ label: 'Planning',
+ titled: true,
+ }),
+ { type: 'text' as const, text: ' project ' },
+ {
+ type: 'mention' as const,
+ kind: 'project' as const,
+ label: 'Cindy',
+ raw: projectHref,
+ href: projectHref,
+ workingDir: '/stale/path',
+ },
+ ],
+ };
+
+ const serialized = serializeComposerDocument(document);
+ expect(serialized.text).toBe(
+ `inspect ${messageHref} continue [Planning](${sessionHref}) project ${projectHref}`,
+ );
+ expect(serialized.agentReferences).toEqual([
+ expect.objectContaining({
+ kind: 'message',
+ href: messageHref,
+ text: fullMessage,
+ }),
+ expect.objectContaining({
+ kind: 'session',
+ href: sessionHref,
+ title: 'Planning',
+ }),
+ expect.objectContaining({
+ kind: 'project',
+ href: projectHref,
+ name: 'Cindy',
+ workingDir: '/repos/cindy',
+ }),
+ ]);
+
+ const restored = composerDocumentFromSerializedMessage(serialized.text, {
+ agentReferences: serialized.agentReferences,
+ });
+ expect(serializeComposerDocument(restored)).toEqual(serialized);
+ });
+
+ it('replaces projected text without changing the surrounding atom', () => {
+ const document = {
+ version: 1 as const,
+ nodes: [
+ { type: 'text' as const, text: 'a' },
+ { type: 'quote' as const, quote: { text: 'q' } },
+ { type: 'text' as const, text: 'b' },
+ ],
+ };
+ expect(replaceComposerTextRange(document, 0, 1, [{ type: 'text', text: 'x' }]).nodes).toEqual([
+ { type: 'text', text: 'x' },
+ { type: 'quote', quote: { text: 'q' } },
+ { type: 'text', text: 'b' },
+ ]);
+ });
+
+ it('preserves quote atoms while voice text appends and clears the whole document explicitly', () => {
+ const document = migrateLegacyComposerDraft('hello', [{ text: 'quote' }]);
+ expect(reconcileComposerProjectedText(document, 'hello world').nodes.map((node) => node.type)).toEqual([
+ 'quote', 'text',
+ ]);
+ expect(reconcileComposerProjectedText(document, '').nodes).toEqual([]);
+ });
+
+ it('drops malformed persisted atom fields at the document boundary', () => {
+ const restored = parseStoredComposerDocument({
+ version: 1,
+ nodes: [
+ { type: 'mention', kind: 'file', label: 42, raw: '@"a"' },
+ { type: 'session-link', href: 'cindy://session/s-1', label: 'session', titled: 'yes' },
+ { type: 'pasted-text', text: 'paste', display: false },
+ { type: 'quote', quote: { text: 'quote', sourcePath: 'a.ts', startLine: 8, endLine: 3 } },
+ { type: 'mention', kind: 'file', label: 'a', raw: '@"a"' },
+ { type: 'quote', quote: { text: 'valid', sourcePath: 'a.ts', startLine: 3, endLine: 8 } },
+ ],
+ });
+
+ expect(restored?.nodes).toEqual([
+ { type: 'mention', kind: 'file', label: 'a', raw: '@"a"' },
+ { type: 'quote', quote: { text: 'valid', sourcePath: 'a.ts', startLine: 3, endLine: 8 } },
+ ]);
+ });
+});
diff --git a/apps/mobile/src/__tests__/composerDraftStore.test.ts b/apps/mobile/src/__tests__/composerDraftStore.test.ts
index ba71720187..d1f1045d37 100644
--- a/apps/mobile/src/__tests__/composerDraftStore.test.ts
+++ b/apps/mobile/src/__tests__/composerDraftStore.test.ts
@@ -78,6 +78,51 @@ describe('composerDraftStore', () => {
await clearComposerDrafts();
});
+ it('persists the semantic document so atom order survives remounts', async () => {
+ const {
+ __testing,
+ flushComposerDraftWrites,
+ readComposerDocumentDraft,
+ readComposerDocumentDraftSync,
+ saveComposerDocumentDraft,
+ } = await import('@/session/composerDraftStore');
+ const document = {
+ version: 1 as const,
+ nodes: [
+ { type: 'quote' as const, quote: { text: 'selected' } },
+ { type: 'text' as const, text: 'reply' },
+ ],
+ };
+
+ saveComposerDocumentDraft('s1', document);
+ expect(readComposerDocumentDraftSync('s1')).toEqual(document);
+ await flushComposerDraftWrites('s1');
+ expect(JSON.parse(store.get(__testing.documentStorageKeyForSession('s1')) ?? '')).toEqual(document);
+ await expect(readComposerDocumentDraft('s1')).resolves.toEqual(document);
+ });
+
+ it('does not let a stale document read replace a newer semantic draft', async () => {
+ const asyncStorage = (await import('@react-native-async-storage/async-storage')).default;
+ const {
+ readComposerDocumentDraft,
+ readComposerDocumentDraftSync,
+ saveComposerDocumentDraft,
+ } = await import('@/session/composerDraftStore');
+ let resolveGetItem!: (value: string | null) => void;
+ vi.mocked(asyncStorage.getItem).mockImplementationOnce(() => new Promise((resolve) => {
+ resolveGetItem = resolve;
+ }));
+ const oldDocument = { version: 1, nodes: [{ type: 'text', text: 'old' }] };
+ const newDocument = { version: 1 as const, nodes: [{ type: 'text' as const, text: 'new' }] };
+
+ const readPromise = readComposerDocumentDraft('s1');
+ saveComposerDocumentDraft('s1', newDocument);
+ resolveGetItem(JSON.stringify(oldDocument));
+
+ await expect(readPromise).resolves.toEqual(newDocument);
+ expect(readComposerDocumentDraftSync('s1')).toEqual(newDocument);
+ });
+
it('clears empty drafts and ignores missing session ids', async () => {
const {
consumeComposerDraft,
@@ -116,6 +161,28 @@ describe('composerDraftStore', () => {
expect(store.get(__testing.storageKeyForSession('s1'))).toBe('rewrite');
});
+ it('debounces semantic document writes while keeping memory current', async () => {
+ vi.useFakeTimers();
+ const asyncStorage = (await import('@react-native-async-storage/async-storage')).default;
+ const {
+ __testing,
+ readComposerDocumentDraftSync,
+ saveComposerDocumentDraft,
+ } = await import('@/session/composerDraftStore');
+ const first = { version: 1 as const, nodes: [{ type: 'text' as const, text: 'r' }] };
+ const latest = { version: 1 as const, nodes: [{ type: 'text' as const, text: 'rewrite' }] };
+
+ saveComposerDocumentDraft('s1', first);
+ saveComposerDocumentDraft('s1', latest);
+
+ expect(readComposerDocumentDraftSync('s1')).toEqual(latest);
+ expect(vi.mocked(asyncStorage.setItem)).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(__testing.persistDebounceMs);
+
+ expect(vi.mocked(asyncStorage.setItem)).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(store.get(__testing.documentStorageKeyForSession('s1')) ?? '')).toEqual(latest);
+ });
+
it('does not let a stale async read overwrite a newer memory draft', async () => {
const asyncStorage = (await import('@react-native-async-storage/async-storage')).default;
const {
diff --git a/apps/mobile/src/__tests__/composerPaste.test.ts b/apps/mobile/src/__tests__/composerPaste.test.ts
new file mode 100644
index 0000000000..e40423e773
--- /dev/null
+++ b/apps/mobile/src/__tests__/composerPaste.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from 'vitest';
+import {
+ composerNodesForBoundedPlainTextPaste,
+ composerNodesForPlainTextPaste,
+} from '@/session/composerPaste';
+import { MAX_PASTED_TEXT_CHARS } from '@/session/composerRichInputProtocol';
+import { serializeComposerDocument } from '@/session/composerDocument';
+
+describe('mobile composer plain-text paste pipeline', () => {
+ it('folds a long paste before inspecting links inside it', () => {
+ const text = Array.from(
+ { length: 24 },
+ (_, index) => `line ${index + 1} cindy://session/session-${index}`,
+ ).join('\n');
+
+ expect(composerNodesForPlainTextPaste(text)).toEqual([{
+ type: 'pasted-text',
+ text,
+ display: 'Pasted text (24 lines)',
+ }]);
+ });
+
+ it('turns bare current and legacy session links into inline atoms', () => {
+ const nodes = composerNodesForPlainTextPaste(
+ 'before cindy://session/session-one and xdt-maker://session/session-two?message=message-2.',
+ );
+
+ expect(nodes).toEqual([
+ { type: 'text', text: 'before ' },
+ {
+ type: 'session-link',
+ href: 'cindy://session/session-one',
+ label: 'session-one',
+ titled: false,
+ },
+ { type: 'text', text: ' and ' },
+ {
+ type: 'session-link',
+ href: 'xdt-maker://session/session-two?message=message-2',
+ label: 'message-2',
+ messageClientId: 'message-2',
+ titled: false,
+ },
+ { type: 'text', text: '.' },
+ ]);
+ });
+
+ it('uses markdown labels for sessions but always resolves message anchors from their body', () => {
+ const nodes = composerNodesForPlainTextPaste(
+ '[[WIP] 会话](cindy://session/session-one) [wrong title](cindy://session/session-two?message=message-2)',
+ );
+
+ expect(nodes).toEqual([
+ {
+ type: 'session-link',
+ href: 'cindy://session/session-one',
+ label: 'WIP 会话',
+ titled: true,
+ },
+ { type: 'text', text: ' ' },
+ {
+ type: 'session-link',
+ href: 'cindy://session/session-two?message=message-2',
+ label: 'message-2',
+ messageClientId: 'message-2',
+ titled: false,
+ },
+ ]);
+ });
+
+ it('turns project deep links into project atoms with desktop-compatible wire text', () => {
+ const text = [
+ '[Mobile App](cindy://project/%2FUsers%2Fdash%2FCode%2FMobile)',
+ ' then ',
+ 'xdt-maker://project/C%3A%5CCode%5CDesktop',
+ ].join('');
+ const nodes = composerNodesForPlainTextPaste(text);
+
+ expect(nodes).toEqual([
+ {
+ type: 'mention',
+ kind: 'project',
+ label: 'Mobile App',
+ raw: '[Mobile App](cindy://project/%2FUsers%2Fdash%2FCode%2FMobile)',
+ href: 'cindy://project/%2FUsers%2Fdash%2FCode%2FMobile',
+ workingDir: '/Users/dash/Code/Mobile',
+ },
+ { type: 'text', text: ' then ' },
+ {
+ type: 'mention',
+ kind: 'project',
+ label: 'Desktop',
+ raw: 'xdt-maker://project/C%3A%5CCode%5CDesktop',
+ href: 'xdt-maker://project/C%3A%5CCode%5CDesktop',
+ workingDir: 'C:\\Code\\Desktop',
+ },
+ ]);
+ expect(serializeComposerDocument({ version: 1, nodes }).text).toBe(text);
+ });
+
+ it('keeps ordinary text as one editable text node', () => {
+ expect(composerNodesForPlainTextPaste('ordinary paste')).toEqual([
+ { type: 'text', text: 'ordinary paste' },
+ ]);
+ });
+
+ it('rejects an oversized native clipboard fallback before constructing nodes', () => {
+ expect(
+ composerNodesForBoundedPlainTextPaste('x'.repeat(MAX_PASTED_TEXT_CHARS + 1)),
+ ).toBeNull();
+ });
+});
diff --git a/apps/mobile/src/__tests__/composerRichInputHtml.test.ts b/apps/mobile/src/__tests__/composerRichInputHtml.test.ts
new file mode 100644
index 0000000000..759a1d2b89
--- /dev/null
+++ b/apps/mobile/src/__tests__/composerRichInputHtml.test.ts
@@ -0,0 +1,190 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { buildComposerRichInputHtml } from '@/session/composerRichInputHtml';
+import { parseComposerWebMessage } from '@/session/composerRichInputProtocol';
+
+describe('mobile composer rich input HTML', () => {
+ const html = buildComposerRichInputHtml({
+ accessibilityLabel: '输入消息',
+ document: { version: 1, nodes: [{ type: 'quote', quote: { text: '<quoted>' } }] },
+ editable: true,
+ maxHeight: 264,
+ placeholder: '发送消息',
+ theme: {
+ background: '#eee',
+ border: '#aaa',
+ chip: '#ddd',
+ focus: '#555',
+ placeholder: '#777',
+ text: '#111',
+ textSecondary: '#333',
+ },
+ });
+
+ it('ships an offline contenteditable protocol with atom deletion and caret placement', () => {
+ expect(html).toContain('contentEditable');
+ expect(html).toContain("event.key === 'Backspace'");
+ expect(html).toContain('placeCaretAroundAtom(atom, event.clientX)');
+ expect(html).toContain('placeCaretAroundAtom(atom, touch.clientX)');
+ expect(html).not.toContain('drag-start');
+ expect(html).not.toContain('touchmove');
+ expect(html).toContain("compositionstart");
+ expect(html).toContain("paste-images-start");
+ expect(html).toContain('.slice(0, MAX_PASTED_IMAGE_COUNT)');
+ expect(html).toContain('SUPPORTED_PASTED_IMAGE_MIME_TYPES.has(mimeType)');
+ expect(html).toContain("post({ type: 'paste-image-failed', requestId, index })");
+ expect(html).toContain("type: 'paste-text-request'");
+ expect(html).toContain("document.createComment('cindy-paste:' + requestId)");
+ expect(html).toContain('commitPaste(requestId, nodes)');
+ expect(html).toContain('resolveSessionLink(href, label)');
+ expect(html).toContain('setConfig(value)');
+ expect(html).toContain("style.setProperty('--chip', config.theme.chip)");
+ expect(html).not.toContain('https://');
+ });
+
+ it('uses the shared compact pill geometry for atoms and slash decorations', () => {
+ expect(html).toContain('padding: 2px 8px');
+ expect(html).toContain('margin-right: 6px');
+ expect(html).toContain('border-radius: 9999px');
+ expect(html).toContain('font-size: 12px');
+ expect(html).toContain('line-height: 20px');
+ expect(html).toContain('position: relative; top: -1px');
+ expect(html).toContain('vertical-align: middle');
+ expect(html).not.toContain('vertical-align: -7px');
+ expect(html).not.toContain('border-radius: 4px');
+ });
+
+ it('keeps the WebKit caret in an editable text anchor after every atom', () => {
+ expect(html).toContain("const CARET_ANCHOR = '\\u200B'");
+ expect(html).toContain('return node.type === \'text\' ? [element] : [element, makeCaretAnchor()]');
+ expect(html).toContain("String(child.nodeValue || '').split(CARET_ANCHOR).join('')");
+ expect(html).toContain('setCaretAfter(inserted[inserted.length - 1], current)');
+ expect(html).toContain('if (isCaretAnchor(container))');
+ expect(html).toContain('removeAtom(atom)');
+ });
+
+ it('escapes bootstrap markup instead of injecting it into the page', () => {
+ expect(html).toContain('\\u003cquoted>');
+ expect(html).not.toContain('"text":"<quoted>"');
+ });
+
+ it('applies a selected slash command and its end-caret placement atomically', () => {
+ const inputSource = readFileSync(
+ resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n');
+ const screenSource = readFileSync(
+ resolve(process.cwd(), 'app/sessions/[sessionId].tsx'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n');
+ const selectStart = screenSource.indexOf('const selectSlashCommand = useCallback');
+ const selectEnd = screenSource.indexOf('const selectAtResource = useCallback', selectStart);
+ const selectSource = screenSource.slice(selectStart, selectEnd);
+
+ expect(inputSource).toContain('applyDocumentAndSetSelectionToEnd(document: ComposerDocument): void;');
+ expect(inputSource).toContain('applyDocumentAndSetSelectionToEnd: (value) => {');
+ expect(inputSource).toContain('applyDocument(value, true);');
+ expect(inputSource).toContain('if (pending) applyDocument(pending.document, pending.focusAfter);');
+ expect(inputSource).toContain('pendingNodeInsertionsRef.current.push(node);');
+ expect(inputSource).toContain('for (const node of pendingNodeInsertions)');
+ expect(selectSource).toContain('queueEditingRef.current ? { persist: false } : undefined');
+ expect(selectSource).toContain('composerInputRef.current?.applyDocumentAndSetSelectionToEnd(nextDocument);');
+ expect(selectSource).not.toContain('composerInputRef.current?.focus();');
+ });
+
+ it('rejects malformed image messages at the WebView boundary', () => {
+ expect(parseComposerWebMessage(JSON.stringify({ type: 'paste-images-start', count: '2' }))).toBeNull();
+ expect(parseComposerWebMessage(JSON.stringify({
+ type: 'paste-images-start',
+ requestId: 'images-1',
+ count: 2,
+ }))).toEqual({
+ type: 'paste-images-start',
+ requestId: 'images-1',
+ count: 2,
+ });
+ expect(parseComposerWebMessage(JSON.stringify({
+ type: 'paste-image-failed',
+ requestId: 'images-1',
+ index: 1,
+ }))).toEqual({
+ type: 'paste-image-failed',
+ requestId: 'images-1',
+ index: 1,
+ });
+ expect(parseComposerWebMessage(JSON.stringify({
+ type: 'paste-image',
+ requestId: 'images-1',
+ base64: '',
+ mimeType: 'image/png',
+ name: 'paste.png',
+ index: 0,
+ }))).toBeNull();
+ expect(parseComposerWebMessage(JSON.stringify({
+ type: 'paste-image',
+ requestId: 'images-1',
+ base64: 'PHN2Zz4=',
+ mimeType: 'image/svg+xml',
+ name: 'paste.svg',
+ index: 0,
+ }))).toBeNull();
+ expect(parseComposerWebMessage(JSON.stringify({
+ type: 'paste-image',
+ requestId: 'images-1',
+ base64: 'aGVsbG8=',
+ mimeType: 'image/png',
+ name: 'paste.png',
+ index: 0,
+ }))).toEqual({
+ type: 'paste-image',
+ requestId: 'images-1',
+ base64: 'aGVsbG8=',
+ mimeType: 'image/png',
+ name: 'paste.png',
+ index: 0,
+ });
+ });
+
+ it('accepts bounded native text-paste requests and rejects malformed ones', () => {
+ expect(parseComposerWebMessage(JSON.stringify({
+ type: 'paste-text-request',
+ requestId: '12',
+ }))).toEqual({
+ type: 'paste-text-request',
+ requestId: '12',
+ });
+ expect(parseComposerWebMessage(JSON.stringify({
+ type: 'paste-text-request',
+ requestId: '13',
+ text: 'cindy://session/a',
+ }))).toEqual({
+ type: 'paste-text-request',
+ requestId: '13',
+ text: 'cindy://session/a',
+ });
+ expect(parseComposerWebMessage(JSON.stringify({
+ type: 'paste-text-request',
+ requestId: 14,
+ text: 'plain',
+ }))).toBeNull();
+ expect(parseComposerWebMessage(JSON.stringify({
+ type: 'paste-text-request',
+ requestId: '15',
+ text: 42,
+ }))).toBeNull();
+ });
+
+ it('falls back to the native clipboard when iOS omits paste clipboardData', () => {
+ const inputSource = readFileSync(
+ resolve(process.cwd(), 'src/session/ComposerRichInput.tsx'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n');
+
+ expect(inputSource).toContain("import * as Clipboard from 'expo-clipboard';");
+ expect(inputSource).toContain('text = await Clipboard.getStringAsync();');
+ expect(inputSource).toContain('composerNodesForBoundedPlainTextPaste(text)');
+ expect(inputSource).toContain('window.cindyComposer.commitPaste(${JSON.stringify(message.requestId)}, []);');
+ expect(inputSource).toContain('window.cindyComposer.commitPaste(');
+ });
+});
diff --git a/apps/mobile/src/__tests__/inputProjection.test.ts b/apps/mobile/src/__tests__/inputProjection.test.ts
index d38a70a877..59fa5446cb 100644
--- a/apps/mobile/src/__tests__/inputProjection.test.ts
+++ b/apps/mobile/src/__tests__/inputProjection.test.ts
@@ -13,6 +13,7 @@ import {
} from '@/session/inputProjection';
import { buildMobileUploadedAttachment } from '@/session/attachments';
import { parseAttachmentOssRef } from '@/session/attachmentOssRef';
+import { textComposerDocument } from '@/session/composerDocument';
import type { RemoteSession } from '@/session/types';
const ATTACHMENT_SHA256 = 'a'.repeat(64);
@@ -130,17 +131,66 @@ describe('inputProjection', () => {
);
const state = createQueueEditTextState(queued);
- expect(state.visibleText).toBe('> selected\n\nreply');
- expect(resolveQueueEditTextSubmission(state, state.visibleText)).toEqual({
+ expect(state.visibleText).toBe('reply');
+ expect(state.document.nodes.map((node) => node.type)).toEqual(['quote', 'text']);
+ expect(resolveQueueEditTextSubmission(state, state.document)).toEqual({
text: encoded,
quotesEncoded: true,
+ agentReferences: [],
});
- expect(resolveQueueEditTextSubmission(state, '> selected\n\nedited')).toEqual({
- text: '> selected\n\nedited',
- quotesEncoded: false,
+ expect(resolveQueueEditTextSubmission(state, {
+ nodes: state.document.nodes.map((node) => ({ ...node })),
+ version: 1,
+ })).toEqual({
+ text: encoded,
+ quotesEncoded: true,
+ agentReferences: [],
+ });
+ expect(resolveQueueEditTextSubmission(state, {
+ version: 1,
+ nodes: [state.document.nodes[0], { type: 'text', text: 'edited' }],
+ })).toEqual({
+ text: '> <!-- cindy-composer-quote -->\n> selected\n\nedited',
+ quotesEncoded: true,
+ agentReferences: [],
+ slashCommandRanges: [],
});
});
+ it('persists structured references through queue creation and queue editing', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const text = `inspect ${href}`;
+ const reference = {
+ kind: 'message' as const,
+ start: text.indexOf(href),
+ end: text.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Complete target message body',
+ };
+ const queued = buildQueuedTextMessage(
+ session(),
+ text,
+ new Date('2026-01-01T00:00:05.000Z'),
+ 'q-reference',
+ { agentReferences: [reference] },
+ );
+
+ expect(queued.agentReferences).toEqual([reference]);
+ expect(JSON.parse(queued.persistedContent).agentReferences).toEqual([reference]);
+ const state = createQueueEditTextState(queued);
+ expect(state.agentReferences).toEqual([reference]);
+ expect(resolveQueueEditTextSubmission(state, state.document).agentReferences)
+ .toEqual([reference]);
+
+ expect(resolveQueueEditTextSubmission(state, textComposerDocument('plain edit')))
+ .toMatchObject({
+ text: 'plain edit',
+ agentReferences: [],
+ });
+ });
+
it('builds queued messages with desktop-compatible remote file attachments', () => {
const queued = buildQueuedTextMessage(session(), 'see attached', new Date('2026-01-01T00:00:04.000Z'), 'q-file', {
attachments: [{
diff --git a/apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts b/apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts
index 70fc862d15..d1bf33b7f4 100644
--- a/apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/messageActionDesktopFirst.test.ts
@@ -10,19 +10,18 @@ describe('mobile message actions desktop-first surface', () => {
expect(source).toContain('const MESSAGE_CONTROL_HIT_SLOP = { bottom: 10, left: 10, right: 10, top: 10 };');
expect(source).toContain('buildMessageActionBarPresentation');
expect(sharedSource).toContain("input.canCopy ? 'copy' : null");
- expect(sharedSource).toContain("input.canFork ? 'fork' : null");
- expect(sharedSource).toContain("input.canDelete ? 'delete' : null");
+ expect(sharedSource).toContain("input.hasMoreActions ? 'more' : null");
expect(sharedSource).toContain("input.hasTime ? 'time' : null");
expect(sharedSource).toContain("input.hasTurnCost ? 'cost' : null");
- expect(sharedSource).toContain("input.hasTime ? 'time' : null");
- expect(sharedSource).toContain("input.canRewind ? 'rewind' : null");
+ expect(source).toContain('<MessageActionSheet');
+ expect(source).toContain('buildMobileMessageMenu({');
expect(source).toContain("&& (item.message.kind === 'user' || item.message.kind === 'assistant')");
expect(source).toContain('&& actions.isSessionStreaming !== true');
expect(source).toContain('hitSlop={MESSAGE_CONTROL_HIT_SLOP}');
expect(source).toContain('buttonSize={actionBar.buttonSize}');
expect(source).toContain('iconSize={actionBar.iconSize}');
- expect(source).toContain("return id === 'copy' || id === 'delete' || id === 'rewind' || id === 'fork';");
- expect(source).toContain("if (id === 'delete') return 'message.deleteButton';");
+ expect(source).toContain("return id === 'copy';");
+ expect(source).toContain('testID="message.moreButton"');
expect(source).toContain('{ height: buttonSize, width: buttonSize }');
expect(source).toContain('height: 24');
expect(source).toContain('width: 24');
@@ -48,6 +47,23 @@ describe('mobile message actions desktop-first surface', () => {
);
});
+ it('only exposes the More menu on a completed turn boundary', () => {
+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
+
+ expect(source).toContain(
+ 'const canCopyLink = !!(showCompletedActionBar && clientId && actions.onCopyMessageLink);',
+ );
+ expect(source).toContain(
+ 'const canAddToChat = !!(showCompletedActionBar && clientId && actions.onAddMessageToComposer);',
+ );
+ expect(source).not.toContain(
+ 'const canCopyLink = !!(canUseCompletedActions && clientId && actions.onCopyMessageLink);',
+ );
+ expect(source).not.toContain(
+ 'const canAddToChat = !!(canUseCompletedActions && clientId && actions.onAddMessageToComposer);',
+ );
+ });
+
it('keeps message controls outside the user bubble like the desktop action bar', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
const bubbleStart = source.indexOf('const bubble = (');
diff --git a/apps/mobile/src/__tests__/messageActionMenu.test.ts b/apps/mobile/src/__tests__/messageActionMenu.test.ts
new file mode 100644
index 0000000000..2afe3259ad
--- /dev/null
+++ b/apps/mobile/src/__tests__/messageActionMenu.test.ts
@@ -0,0 +1,31 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { buildMobileMessageMenu } from '@/session/messageActionMenu';
+
+describe('mobile message action menu', () => {
+ it('matches desktop order, natural language, and destructive grouping', () => {
+ expect(buildMobileMessageMenu({
+ canAddToChat: true,
+ canCopyLink: true,
+ canDelete: true,
+ canFork: true,
+ canRewind: true,
+ })).toEqual([
+ { id: 'fork', label: '在新对话中继续' },
+ { id: 'add-to-chat', label: '添加到对话' },
+ { id: 'copy-link', label: '复制当前对话链接' },
+ { id: 'rewind', label: '回到此处' },
+ { id: 'delete', label: '删除本条对话', destructive: true, separatorBefore: true },
+ ]);
+ });
+
+ it('reuses the shared sheet lifecycle and dispatches a choice after close', () => {
+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageActionSheet.tsx'), 'utf8');
+ expect(source).toContain('<SheetModal');
+ expect(source).toContain('onClosed={handleClosed}');
+ expect(source).toContain('pendingActionRef.current = action');
+ expect(source).not.toContain('<Modal');
+ expect(source).not.toContain('Animated.timing');
+ });
+});
diff --git a/apps/mobile/src/__tests__/messageMarkdown.test.ts b/apps/mobile/src/__tests__/messageMarkdown.test.ts
index cfb65ae3e6..bfe0b5c7ff 100644
--- a/apps/mobile/src/__tests__/messageMarkdown.test.ts
+++ b/apps/mobile/src/__tests__/messageMarkdown.test.ts
@@ -906,6 +906,18 @@ describe('messageMarkdown', () => {
]);
});
+ it('keeps session deep links literal inside inline and fenced code', () => {
+ const url = 'cindy://session/session-a?message=message-a';
+ expect(parseMobileMarkdownInlines(`\`${url}\` then ${url}`)).toEqual([
+ { type: 'code', text: url },
+ { type: 'text', text: ' then ' },
+ { type: 'link', text: url, url },
+ ]);
+ expect(parseMobileMarkdown(['```text', url, '```'].join('\n'))).toEqual([
+ { type: 'code', key: 'code:0:0', language: 'text', text: url },
+ ]);
+ });
+
it('tokenizes bare and explicit project deep links as inline links (review P1)', () => {
// 桌面端粘贴 chip 化后按 [标题](深链) 发送;不 tokenize 会把整段渲染成
// 原始 markdown 源码。renderInline 对非 session 深链显示 label 纯文本。
diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.ts
index 3d0fe63a20..10d468de69 100644
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@ -3,6 +3,7 @@ import {
CONTINUE_AFTER_ERROR_PROMPT,
UI_ACTION_TRIGGER_PREFIX,
} from '@cindy/maker-shared/synthetic-trigger';
+import { composerDocumentFromSerializedMessage } from '@/session/composerDocument';
import { normalizeRemoteMessages } from '@/session/messageNormalize';
import type { RemoteMessage } from '@/session/types';
@@ -215,6 +216,88 @@ describe('normalizeRemoteMessages', () => {
expect(invalid.sessionReferences).toEqual([]);
});
+ it('preserves valid pasted-text and exact slash presentation ranges', () => {
+ const text = '/help before long text after';
+ const [item] = normalizeRemoteMessages([
+ message({
+ id: 'atomic-user',
+ role: 'user',
+ content: JSON.stringify({
+ text,
+ images: [],
+ files: [],
+ pastedTextRanges: [{ start: 13, end: 22, display: 'Pasted text (1 line)' }],
+ slashCommandRanges: [{ start: 0, end: 5 }],
+ }),
+ }),
+ ]);
+
+ expect(item).toMatchObject({
+ pastedTextRanges: [{ start: 13, end: 22, display: 'Pasted text (1 line)' }],
+ slashCommandRanges: [{ start: 0, end: 5 }],
+ });
+ });
+
+ it('preserves message reference semantics when fork or rewind rebuilds the composer', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const text = `inspect ${href}`;
+ const reference = {
+ kind: 'message' as const,
+ start: text.indexOf(href),
+ end: text.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Target message body',
+ };
+ const [item] = normalizeRemoteMessages([
+ message({
+ id: 'referenced-user',
+ role: 'user',
+ content: JSON.stringify({
+ text,
+ images: [],
+ files: [],
+ agentReferences: [reference],
+ }),
+ }),
+ ]);
+
+ expect(item.agentReferences).toEqual([reference]);
+ expect(composerDocumentFromSerializedMessage(item.body, {
+ agentReferences: item.agentReferences,
+ }).nodes).toEqual([
+ { type: 'text', text: 'inspect ' },
+ {
+ type: 'session-link',
+ href,
+ label: 'Target message body',
+ messageClientId: 'message-a',
+ titled: true,
+ agentText: 'Target message body',
+ },
+ ]);
+ });
+
+ it('drops malformed atom ranges as whole sets while preserving explicit empty slash metadata', () => {
+ const [item] = normalizeRemoteMessages([
+ message({
+ id: 'malformed-atomic-user',
+ role: 'user',
+ content: {
+ text: 'abcdef',
+ images: [],
+ files: [],
+ pastedTextRanges: [{ start: 1, end: 4, display: 'first' }, { start: 3, end: 5, display: 'overlap' }],
+ slashCommandRanges: [],
+ },
+ }),
+ ]);
+
+ expect(item.pastedTextRanges).toBeUndefined();
+ expect(item.slashCommandRanges).toEqual([]);
+ });
+
it('summarizes tool_use, attaches matching tool_result, and hides standalone tool_result', () => {
const items = normalizeRemoteMessages([
message({
diff --git a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
index e8870f06fe..623c16dcf4 100644
--- a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
+++ b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
@@ -254,15 +254,17 @@ describe('native e2e environment', () => {
it('sends the realtime voice draft returned by the controller instead of stale React state', () => {
const sessionScreen = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
+ expect(sessionScreen).toContain('const documentBeforeStop = composerDocumentRef.current;');
expect(sessionScreen).toContain('const latestDraft = await controller.stop();');
- expect(sessionScreen).toContain('await sendLatest({ draftOverride: latestDraft });');
- expect(sessionScreen.indexOf('const latestDraft = await controller.stop();')).toBeLessThan(
- sessionScreen.indexOf('await sendLatest({ draftOverride: latestDraft });'),
+ expect(sessionScreen).toContain('await sendLatest({ documentOverride: latestDocument });');
+ expect(sessionScreen.indexOf('const documentBeforeStop = composerDocumentRef.current;')).toBeLessThan(
+ sessionScreen.indexOf('const latestDraft = await controller.stop();'),
);
+ expect(sessionScreen).toContain('const latestDocument = latestDraft.trim()');
expect(sessionScreen).toContain('readCurrentDraft: () => draftRef.current');
expect(sessionScreen).toContain('onDraftChanged: setComposerDraft');
expect(sessionScreen).toContain('createMobileVoiceControllerSession({');
- expect(sessionScreen).not.toContain('await sendLatest({ draftOverride: draft });');
+ expect(sessionScreen).not.toContain('await sendLatest({ draftOverride: latestDraft });');
});
it('guards the mobile voice composer against the legacy desktop transcription path', () => {
diff --git a/apps/mobile/src/__tests__/sentMessageAtoms.test.ts b/apps/mobile/src/__tests__/sentMessageAtoms.test.ts
new file mode 100644
index 0000000000..d4b7131d15
--- /dev/null
+++ b/apps/mobile/src/__tests__/sentMessageAtoms.test.ts
@@ -0,0 +1,66 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { formatQuoteForSend, parseChatQuoteSegments } from '@cindy/maker-shared/chat-quotes';
+import {
+ buildSentInlineTokens,
+ buildVisibleSentInlineTokens,
+ sentInlineTokensDisplayText,
+} from '@/session/sentMessageAtoms';
+
+describe('sent message atoms', () => {
+ it('keeps atom chips while rendering ordinary chunks with full Markdown semantics', () => {
+ const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
+ const bodyStart = source.indexOf('function SentInlineAtomBody');
+ const bodyEnd = source.indexOf('function MarkdownBody', bodyStart);
+ const bodySource = source.slice(bodyStart, bodyEnd);
+
+ expect(bodySource).toContain('<InlineQuoteChip');
+ expect(bodySource).toContain('<InlineReferenceChip');
+ expect(bodySource).toContain('<MarkdownBody');
+ expect(bodySource).toContain('text={token.text}');
+ expect(bodySource).not.toContain('splitAnchoredSessionMessageLinks');
+ expect(bodySource).not.toContain('<SentMessageAnchorChip');
+ expect(bodySource).not.toContain('parseMobileMarkdownInlines(part.text)');
+ });
+
+ it('splits exact pasted-text and slash ranges without guessing', () => {
+ const text = '/compact before first\nsecond after';
+ expect(buildSentInlineTokens(
+ text,
+ [{ start: 16, end: 28, display: 'Pasted text (2 lines)' }],
+ [{ start: 0, end: 8 }],
+ )).toEqual([
+ { kind: 'slash', text: '/compact' },
+ { kind: 'text', text: ' before ' },
+ { kind: 'pasted', text: 'first\nsecond', display: 'Pasted text (2 lines)' },
+ { kind: 'text', text: ' after' },
+ ]);
+ });
+
+ it('preserves quote/text order while projecting atom ranges around quote blocks', () => {
+ const quoteA = formatQuoteForSend({ text: 'quoted A' });
+ const quoteB = formatQuoteForSend({ text: 'quoted B', sourcePath: 'src/b.ts' });
+ const source = `${quoteA}\n\n/help before\n\n${quoteB}\n\nlong\ntext after`;
+ const pasteStart = source.indexOf('long\ntext');
+ const slashStart = source.indexOf('/help');
+ const tokens = buildVisibleSentInlineTokens(
+ source,
+ parseChatQuoteSegments(source),
+ [{ start: pasteStart, end: pasteStart + 9, display: 'Pasted text (2 lines)' }],
+ [{ start: slashStart, end: slashStart + 5 }],
+ );
+
+ expect(tokens).toEqual([
+ { kind: 'quote', quote: { text: 'quoted A' } },
+ { kind: 'slash', text: '/help' },
+ { kind: 'text', text: ' before' },
+ { kind: 'quote', quote: { text: 'quoted B', sourcePath: 'src/b.ts' } },
+ { kind: 'pasted', text: 'long\ntext', display: 'Pasted text (2 lines)' },
+ { kind: 'text', text: ' after' },
+ ]);
+ expect(sentInlineTokensDisplayText(tokens)).toBe(
+ 'quoted A\n/help before\nquoted B\nPasted text (2 lines) after',
+ );
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index aba281f0d6..4e1a7a45ca 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -18,7 +18,7 @@ describe('mobile session composer desktop-first surface', () => {
const sharedSource = readTextLf(resolve(process.cwd(), 'src/session/MobileComposerInputRow.tsx'), 'utf8');
const attachmentTraySource = readTextLf(resolve(process.cwd(), 'src/session/ComposerAttachmentTray.tsx'), 'utf8');
const composerInputStart = source.indexOf('<MobileComposerInputRow');
- const composerInputEnd = source.indexOf('/>', composerInputStart) + 2;
+ const composerInputEnd = source.indexOf('/>', source.indexOf('value={draft}', composerInputStart)) + 2;
const composerInputSource = source.slice(composerInputStart, composerInputEnd);
const attachmentButtonStart = source.indexOf('const renderComposerAttachmentButton = () => (');
const attachmentButtonEnd = source.indexOf('const renderComposerTrailingActions = () => (', attachmentButtonStart);
@@ -196,6 +196,9 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).not.toContain('renderComposerTextInput(false)');
expect(source).not.toContain('const renderComposerTextInput = () => (');
expect(composerInputSource).toContain('<MobileComposerInputRow');
+ expect(composerInputSource).toContain('<ComposerRichInput');
+ expect(composerInputSource).toContain('document={composerDocument}');
+ expect(composerInputSource).toContain('inputElement={(');
expect(source).toContain("import { DEVICE_LINK_API_BASE_URL, MOBILE_VISUAL_MOCK_ENABLED } from '@/config/env';");
expect(source).toContain("const visualFocusComposer = MOBILE_VISUAL_MOCK_ENABLED && readRouteParam(params.visualFocusComposer) === '1';");
expect(source).toContain("const visualOpenSearch = MOBILE_VISUAL_MOCK_ENABLED && readRouteParam(params.visualOpenSearch) === '1';");
@@ -280,10 +283,12 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('const COMPOSER_CONTROL_HIT_SLOP = { bottom: 8, left: 8, right: 8, top: 8 };');
expect(source.match(/hitSlop={COMPOSER_CONTROL_HIT_SLOP}/g)?.length ?? 0).toBeGreaterThanOrEqual(3);
expect(source).toContain('const composerHasText = draft.trim().length > 0;');
- expect(source).toContain('const composerQuoteCount = queueEditing ? 0 : quotes.length;');
+ expect(source).toContain('const composerQuoteCount = composerDocumentQuotes(composerDocument).length;');
expect(source).toContain('const composerHasPayload = composerHasText || attachments.length > 0 || pendingUploads.length > 0 || composerQuoteCount > 0;');
expect(source).toContain('const composerShowSendButton = composerLayout.send.visible && (!voiceIsListening || composerHasPayload);');
- expect(source).toContain('if (options.sendAfterTranscribe && (latestDraft.trim() || attachments.length > 0 || getQuotes(sessionId).length > 0))');
+ expect(source).toContain('const latestDocument = latestDraft.trim()');
+ expect(source).toContain('reconcileComposerProjectedText(documentBeforeStop, latestDraft)');
+ expect(source).toContain('if (options.sendAfterTranscribe && (composerDocumentHasContent(latestDocument) || attachments.length > 0))');
expect(source).toContain('const currentTurnStreaming = useMemo(');
expect(source).toContain('const canStopCurrentRun = (remoteSessionRunning || currentTurnStreaming)');
expect(source).toContain('const canStopComposer = canStopQueue || canStopCurrentRun;');
@@ -301,13 +306,14 @@ describe('mobile session composer desktop-first surface', () => {
expect(voiceStatusIndex).toBeLessThan(composerScrollIndex);
expect(source).toContain('testID="session.voiceMicCaret"');
expect(sharedSource).toContain('export function VoiceMicWaveCaret');
- expect(source).toContain('const composerInputRef = useRef<NativeTextInput>(null);');
+ expect(source).toContain('const composerInputRef = useRef<ComposerRichInputHandle | null>(null);');
expect(source).toContain('const voiceDraftScrollRef = useRef<ScrollView>(null);');
- expect(composerInputSource).toContain('inputRef={composerInputRef}');
+ expect(composerInputSource).toContain('ref={composerInputRef}');
+ expect(composerInputSource).not.toContain('inputRef={composerInputRef}');
expect(sharedSource).toContain('ref={inputRef as never}');
expect(source).toContain('ref={voiceDraftScrollRef}');
expect(source).toContain('contentContainerStyle={styles.voiceDraftOverlayContent}');
- expect(source).toContain('composerInputRef.current?.setNativeProps({ selection: { start: end, end } });');
+ expect(source).toContain('composerInputRef.current?.setSelectionToEnd();');
expect(source).toContain('voiceDraftScrollRef.current?.scrollToEnd({ animated: false });');
expect(source).toContain('caretHidden={voiceIsListening}');
expect(source).toContain('const handleComposerInputPressIn = useCallback(() => {');
@@ -431,15 +437,24 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('const composerSendSlotIsStop');
expect(source).toContain('messageListFollowLatestRequestKey');
expect(source).toContain('requestMessageListFollowLatest();');
- expect(source).toContain('const sendLatestRef = useRef<((options?: { draftOverride?: string }) => Promise<void>) | null>(null);');
- expect(source).toContain('await sendLatest({ draftOverride: latestDraft });');
+ expect(source).toContain('documentOverride?: ComposerDocument;');
+ expect(source).toContain('const documentBeforeStop = composerDocumentRef.current;');
+ expect(source).toContain('await sendLatest({ documentOverride: latestDocument });');
expect(source).toContain('sendLatestRef.current = send;');
- expect(source).toContain('if (!canUseComposer) {\n if (options.draftOverride !== undefined) setComposerDraft(options.draftOverride);\n return;\n }');
- expect(source).toContain('flushComposerDraftWrites, readComposerDraft, readComposerDraftSync, saveComposerDraft');
- expect(source).toContain('saveComposerDraft(sessionId, value)');
+ expect(source).toContain('if (options.documentOverride) applyComposerDocument(options.documentOverride);');
+ expect(source).toContain('flushComposerDraftWrites,');
+ expect(source).toContain('readComposerDocumentDraft,');
+ expect(source).toContain('readComposerDocumentDraftSync,');
+ expect(source).toContain('saveComposerDocumentDraft,');
+ expect(source).toContain('saveComposerDocumentDraft(sessionId, value);');
+ expect(source).toContain('saveComposerDraft(sessionId, projected);');
expect(source).toContain('void flushComposerDraftWrites(sessionId);');
expect(source).toContain('readComposerDraftSync(sessionId)');
- expect(source).toContain('draftRef.current !== immediateDraft');
+ expect(source).toContain('const immediateDocumentSnapshot = immediateDocument;');
+ expect(source).toContain('const quoteHydration = immediateQuotes.length > 0');
+ expect(source).toContain(': hydrateQuotes(sessionId);');
+ expect(source).toContain('quoteHydration,');
+ expect(source).toContain('!composerDocumentsEqual(composerDocumentRef.current, immediateDocumentSnapshot)');
expect(source).toContain('if (canUseComposer) return;');
expect(source).toContain('setModelSheetOpen(false);');
expect(source).toContain('if (!canUseComposer || !currentSession || !modelSheetSelection) return;');
@@ -530,7 +545,7 @@ describe('mobile session composer desktop-first surface', () => {
const voiceEnd = source.indexOf('const removeRemoteFileAttachment = useCallback', voiceStart);
const voiceSource = source.slice(voiceStart, voiceEnd);
const composerInputStart = source.indexOf('<MobileComposerInputRow');
- const composerInputEnd = source.indexOf('/>', composerInputStart) + 2;
+ const composerInputEnd = source.indexOf('/>', source.indexOf('value={draft}', composerInputStart)) + 2;
const composerInputSource = source.slice(composerInputStart, composerInputEnd);
expect(voiceSource).toContain('readCurrentDraft: () => draftRef.current');
@@ -547,8 +562,9 @@ describe('mobile session composer desktop-first surface', () => {
voiceSource.indexOf('requestRecordingPermissionsAsync()'),
);
expect(voiceSource).toContain('MOBILE_VOICE_REALTIME_AUDIO_UNAVAILABLE_ERROR');
+ expect(voiceSource).toContain('const documentBeforeStop = composerDocumentRef.current;');
expect(voiceSource).toContain('const latestDraft = await controller.stop();');
- expect(voiceSource).toContain('await sendLatest({ draftOverride: latestDraft });');
+ expect(voiceSource).toContain('await sendLatest({ documentOverride: latestDocument });');
expect(composerInputSource).toContain('inputTestID="session.composerInput"');
expect(sharedSource).toContain('testID={inputTestID}');
expect(composerInputSource).toContain('value={draft}');
diff --git a/apps/mobile/src/__tests__/sessionMessageText.test.ts b/apps/mobile/src/__tests__/sessionMessageText.test.ts
new file mode 100644
index 0000000000..80f113c5a5
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionMessageText.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+import { formatQuoteForSend } from '@cindy/maker-shared/chat-quotes';
+import {
+ mobileSessionMessageDisplayText,
+ splitAnchoredSessionMessageLinks,
+} from '@/session/sessionMessageText';
+import type { RemoteMessage } from '@/session/types';
+
+function message(input: Partial<RemoteMessage>): RemoteMessage {
+ return { id: 'm', role: 'user', content: '', createdAt: '2026-07-23T00:00:00Z', ...input } as RemoteMessage;
+}
+
+describe('mobile session message labels', () => {
+ it('uses visible prose and hides quote markers', () => {
+ expect(mobileSessionMessageDisplayText(message({
+ content: JSON.stringify({
+ text: `${formatQuoteForSend({ text: 'source' })}\n\nanswer`,
+ quotesEncoded: true,
+ }),
+ }))).toBe('answer');
+ });
+
+ it('does not stringify tool metadata', () => {
+ expect(mobileSessionMessageDisplayText(message({ role: 'tool_use', content: { secret: true } }))).toBeNull();
+ });
+
+ it('splits message anchors while preserving adjacent punctuation and whole-session links', () => {
+ expect(splitAnchoredSessionMessageLinks(
+ 'See cindy://session/s-1?message=m-2, then cindy://session/s-3.',
+ )).toEqual([
+ { kind: 'text', text: 'See ' },
+ {
+ kind: 'message-link',
+ url: 'cindy://session/s-1?message=m-2',
+ sessionId: 's-1',
+ messageClientId: 'm-2',
+ },
+ { kind: 'text', text: ', then cindy://session/s-3.' },
+ ]);
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionOutbox.test.ts b/apps/mobile/src/__tests__/sessionOutbox.test.ts
index e53cedc8a5..ddc12fa2e8 100644
--- a/apps/mobile/src/__tests__/sessionOutbox.test.ts
+++ b/apps/mobile/src/__tests__/sessionOutbox.test.ts
@@ -15,6 +15,7 @@ import {
replaceOutboxItem,
} from '@/session/sessionOutbox';
import type { RemoteSerializedAttachment } from '@/session/types';
+import { serializeComposerDocument } from '@/session/composerDocument';
function attachmentFor(name: string): RemoteSerializedAttachment {
return {
@@ -89,6 +90,23 @@ describe('buildOutboxItem', () => {
expect(item.sessionRefs).toEqual(sessionRefs);
expect(item.sessionRefs).not.toBe(sessionRefs);
});
+
+ it('keeps structured reference metadata until dispatch', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const text = `inspect ${href}`;
+ const reference = {
+ kind: 'message' as const,
+ start: text.indexOf(href),
+ end: text.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Complete target message body',
+ };
+
+ expect(itemWith({ text, agentReferences: [reference] }).agentReferences)
+ .toEqual([reference]);
+ });
});
describe('recoverOutboxItemsToComposerDraft', () => {
@@ -106,15 +124,17 @@ describe('recoverOutboxItemsToComposerDraft', () => {
].join('\n');
const item = itemWith({ text: encoded, quotesEncoded: true });
- expect(recoverOutboxItemsToComposerDraft([item], {
+ const recovery = recoverOutboxItemsToComposerDraft([item], {
visibleText: 'new draft',
encodedBody: 'new draft',
quotes: [],
- })).toEqual({
+ });
+ expect(recovery).toMatchObject({
visibleText: 'reply\n\nmore\n\nnew draft',
encodedBody: `${encoded}\n\nnew draft`,
quotes: [{ text: 'selected' }, { text: 'second' }],
});
+ expect(serializeComposerDocument(recovery.document).text).toBe(`${encoded}\n\nnew draft`);
});
it('keeps existing quoted draft metadata aligned after outbox recovery', () => {
@@ -131,30 +151,71 @@ describe('recoverOutboxItemsToComposerDraft', () => {
'existing reply',
].join('\n');
- expect(recoverOutboxItemsToComposerDraft(
+ const recovery = recoverOutboxItemsToComposerDraft(
[itemWith({ text: recoveredEncoded, quotesEncoded: true })],
{
visibleText: 'existing reply',
encodedBody: existingEncoded,
quotes: [{ text: 'existing quote' }],
},
- )).toEqual({
+ );
+ expect(recovery).toMatchObject({
visibleText: 'recovered reply\n\nexisting reply',
encodedBody: `${recoveredEncoded}\n\n${existingEncoded}`,
quotes: [{ text: 'recovered quote' }, { text: 'existing quote' }],
});
+ expect(serializeComposerDocument(recovery.document).text).toBe(
+ `${recoveredEncoded}\n\n${existingEncoded}`,
+ );
});
it('keeps markerless legacy parsing leading-only during salvage', () => {
const encoded = '> old quote\n\nHere:\n> user markdown';
const item = itemWith({ text: encoded, quotesEncoded: true });
- expect(recoverOutboxItemsToComposerDraft([item])).toEqual({
+ expect(recoverOutboxItemsToComposerDraft([item])).toMatchObject({
visibleText: 'Here:\n> user markdown',
encodedBody: encoded,
quotes: [{ text: 'old quote' }],
});
});
+
+ it('restores pasted-text and slash atoms instead of flattening failed attachment sends', () => {
+ const item = itemWith({
+ text: '/help before long\ntext after',
+ pastedTextRanges: [{ start: 13, end: 22, display: 'Pasted text (2 lines)' }],
+ slashCommandRanges: [{ start: 0, end: 5 }],
+ });
+ const recovery = recoverOutboxItemsToComposerDraft([item]);
+
+ expect(recovery.document.nodes.map((node) => node.type)).toEqual([
+ 'text', 'text', 'pasted-text', 'text',
+ ]);
+ expect(serializeComposerDocument(recovery.document)).toMatchObject({
+ pastedTextRanges: [{ start: 13, end: 22, display: 'Pasted text (2 lines)' }],
+ slashCommandRanges: [{ start: 0, end: 5 }],
+ });
+ });
+
+ it('restores message references instead of flattening them to private URIs', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const text = `inspect ${href}`;
+ const reference = {
+ kind: 'message' as const,
+ start: text.indexOf(href),
+ end: text.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Complete target message body',
+ };
+ const recovery = recoverOutboxItemsToComposerDraft([
+ itemWith({ text, agentReferences: [reference] }),
+ ]);
+
+ expect(serializeComposerDocument(recovery.document).agentReferences)
+ .toEqual([reference]);
+ });
});
describe('outboxItemWithUpload / outboxItemWithUploadFailure', () => {
diff --git a/apps/mobile/src/session/ComposerRichInput.tsx b/apps/mobile/src/session/ComposerRichInput.tsx
new file mode 100644
index 0000000000..5727d87266
--- /dev/null
+++ b/apps/mobile/src/session/ComposerRichInput.tsx
@@ -0,0 +1,403 @@
+import { forwardRef, useCallback, useEffect, useMemo, useRef } from 'react';
+import { StyleSheet } from 'react-native';
+import { WebView, type WebViewMessageEvent } from 'react-native-webview';
+import { File, Paths } from 'expo-file-system';
+import * as Clipboard from 'expo-clipboard';
+import {
+ normalizeComposerDocument,
+ parseStoredComposerDocument,
+ type ComposerDocument,
+ type ComposerNode,
+ type ResolvedSessionLinkSemantic,
+} from '@/session/composerDocument';
+import { composerNodesForBoundedPlainTextPaste } from '@/session/composerPaste';
+import { buildComposerRichInputHtml, type ComposerRichInputTheme } from '@/session/composerRichInputHtml';
+import {
+ parseComposerWebMessage,
+ type ComposerWebMessage,
+} from '@/session/composerRichInputProtocol';
+import { COMPOSER_PASTED_IMAGE_FILE_PREFIX } from '@/session/pastedImageAttachment';
+
+export interface ComposerRichInputHandle {
+ applyDocumentAndSetSelectionToEnd(document: ComposerDocument): void;
+ blur(): void;
+ focus(): void;
+ insertNode(node: ComposerNode): void;
+ setSelectionToEnd(): void;
+}
+
+export interface ComposerRichInputProps {
+ accessibilityHint?: string;
+ accessibilityLabel: string;
+ document: ComposerDocument;
+ editable?: boolean;
+ height: number;
+ hidden?: boolean;
+ maxHeight: number;
+ onBlur?: () => void;
+ onChangeDocument(document: ComposerDocument): void;
+ onFocus?: () => void;
+ onHeightChange?: (height: number) => void;
+ onPasteImages?: (uris: string[]) => void;
+ onPasteImagesLoadFailed?: () => void;
+ onPasteImagesLoading?: (count: number) => void;
+ placeholder: string;
+ resolveSessionLinkLabel?: (href: string) => Promise<ResolvedSessionLinkSemantic | null>;
+ testID?: string;
+ theme: ComposerRichInputTheme;
+}
+
+interface PendingImagePaste {
+ expectedCount: number;
+ settledIndexes: Set<number>;
+ urisByIndex: Map<number, string>;
+}
+
+/** Editable WebView wrapper; the native side only accepts the semantic protocol above. */
+export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRichInputProps>(
+ function ComposerRichInput({
+ accessibilityHint,
+ accessibilityLabel,
+ document,
+ editable = true,
+ height,
+ hidden = false,
+ maxHeight,
+ onBlur,
+ onChangeDocument,
+ onFocus,
+ onHeightChange,
+ onPasteImages,
+ onPasteImagesLoadFailed,
+ onPasteImagesLoading,
+ placeholder,
+ resolveSessionLinkLabel,
+ testID,
+ theme,
+ }, forwardedRef) {
+ const webViewRef = useRef<WebView | null>(null);
+ const readyRef = useRef(false);
+ const webSignatureRef = useRef('');
+ const pendingDocumentRef = useRef<{
+ document: ComposerDocument;
+ focusAfter: boolean;
+ } | null>(null);
+ const pendingFocusRef = useRef(false);
+ const pendingNodeInsertionsRef = useRef<ComposerNode[]>([]);
+ const pendingImagePastesRef = useRef(new Map<string, PendingImagePaste>());
+ const pendingImagePasteOrderRef = useRef<string[]>([]);
+ const pastedImageFileSequenceRef = useRef(0);
+ /** 尚未交接给附件上传 hook 的 WebView 粘贴缓存文件。 */
+ const pendingPastedImageFilesRef = useRef(new Set<string>());
+ const disposedRef = useRef(false);
+ const initialConfigRef = useRef({
+ accessibilityLabel,
+ document,
+ editable,
+ maxHeight,
+ placeholder,
+ theme,
+ });
+ const html = useMemo(
+ () => buildComposerRichInputHtml(initialConfigRef.current),
+ [],
+ );
+ const runtimeConfig = useMemo(() => ({
+ accessibilityLabel,
+ editable,
+ maxHeight,
+ placeholder,
+ theme,
+ }), [
+ accessibilityLabel,
+ editable,
+ maxHeight,
+ placeholder,
+ theme.background,
+ theme.border,
+ theme.chip,
+ theme.focus,
+ theme.placeholder,
+ theme.text,
+ theme.textSecondary,
+ ]);
+
+ const inject = useCallback((script: string) => {
+ webViewRef.current?.injectJavaScript(`try { ${script} } catch (_) {} true;`);
+ }, []);
+ const focusEditor = useCallback(() => {
+ if (!readyRef.current) {
+ pendingFocusRef.current = true;
+ return;
+ }
+ inject('window.cindyComposer.focus();');
+ }, [inject]);
+ const applyDocument = useCallback((value: ComposerDocument, focusAfter = false) => {
+ if (!readyRef.current) {
+ pendingDocumentRef.current = { document: value, focusAfter };
+ return;
+ }
+ inject(`window.cindyComposer.applyDocument(${JSON.stringify(value)}, ${focusAfter});`);
+ }, [inject]);
+
+ useEffect(() => {
+ const signature = JSON.stringify(document);
+ if (signature === webSignatureRef.current) return;
+ webSignatureRef.current = signature;
+ applyDocument(document);
+ }, [applyDocument, document]);
+ useEffect(() => {
+ inject(`window.cindyComposer.setConfig(${JSON.stringify(runtimeConfig)});`);
+ }, [inject, runtimeConfig]);
+
+ useEffect(() => {
+ if (!forwardedRef) return undefined;
+ const handle: ComposerRichInputHandle = {
+ applyDocumentAndSetSelectionToEnd: (value) => {
+ webSignatureRef.current = JSON.stringify(value);
+ applyDocument(value, true);
+ },
+ blur: () => {
+ pendingFocusRef.current = false;
+ if (pendingDocumentRef.current?.focusAfter) {
+ pendingDocumentRef.current = {
+ ...pendingDocumentRef.current,
+ focusAfter: false,
+ };
+ }
+ if (readyRef.current) inject('window.cindyComposer.blur();');
+ },
+ focus: focusEditor,
+ insertNode: (node) => {
+ if (!readyRef.current) {
+ pendingNodeInsertionsRef.current.push(node);
+ return;
+ }
+ inject(`window.cindyComposer.insertNode(${JSON.stringify(node)});`);
+ },
+ setSelectionToEnd: focusEditor,
+ };
+ if (typeof forwardedRef === 'function') forwardedRef(handle);
+ else forwardedRef.current = handle;
+ return () => {
+ if (typeof forwardedRef === 'function') forwardedRef(null);
+ else forwardedRef.current = null;
+ };
+ }, [applyDocument, focusEditor, forwardedRef, inject]);
+
+ const persistPastedImage = useCallback(async (
+ message: Extract<ComposerWebMessage, { type: 'paste-image' }>,
+ ): Promise<string> => {
+ if (!message.base64) throw new Error('empty pasted image');
+ const extension = extensionForMime(message.mimeType);
+ const sequence = ++pastedImageFileSequenceRef.current;
+ const file = new File(
+ Paths.cache,
+ `${COMPOSER_PASTED_IMAGE_FILE_PREFIX}${Date.now()}-${sequence}.${extension}`,
+ );
+ const FileSystem = await import('expo-file-system/legacy');
+ pendingPastedImageFilesRef.current.add(file.uri);
+ try {
+ await FileSystem.writeAsStringAsync(file.uri, message.base64, {
+ encoding: FileSystem.EncodingType.Base64,
+ });
+ if (disposedRef.current) {
+ throw new Error('composer disposed during pasted image write');
+ }
+ return file.uri;
+ } catch (error) {
+ await FileSystem.deleteAsync(file.uri, { idempotent: true }).catch(() => undefined);
+ pendingPastedImageFilesRef.current.delete(file.uri);
+ throw error;
+ }
+ }, []);
+
+ const drainCompletedImagePastes = useCallback(() => {
+ while (pendingImagePasteOrderRef.current.length > 0) {
+ const requestId = pendingImagePasteOrderRef.current[0];
+ const batch = pendingImagePastesRef.current.get(requestId);
+ if (!batch || batch.settledIndexes.size < batch.expectedCount) return;
+ pendingImagePasteOrderRef.current.shift();
+ pendingImagePastesRef.current.delete(requestId);
+ const uris = [...batch.urisByIndex.entries()]
+ .sort(([left], [right]) => left - right)
+ .map(([, uri]) => uri);
+ if (uris.length > 0 && onPasteImages) {
+ // 所有权在调用前转交上传 hook;后续成功 / 失败 / 取消由其负责清理。
+ for (const uri of uris) pendingPastedImageFilesRef.current.delete(uri);
+ onPasteImages(uris);
+ } else {
+ if (uris.length > 0) {
+ for (const uri of uris) pendingPastedImageFilesRef.current.delete(uri);
+ void deleteComposerPastedImageUris(uris);
+ }
+ onPasteImagesLoadFailed?.();
+ }
+ }
+ }, [onPasteImages, onPasteImagesLoadFailed]);
+
+ useEffect(() => {
+ disposedRef.current = false;
+ return () => {
+ disposedRef.current = true;
+ const pendingUris = [...pendingPastedImageFilesRef.current];
+ pendingPastedImageFilesRef.current.clear();
+ if (pendingUris.length > 0) void deleteComposerPastedImageUris(pendingUris);
+ };
+ }, []);
+
+ const settlePastedImage = useCallback((
+ requestId: string,
+ index: number,
+ uri?: string,
+ ) => {
+ const batch = pendingImagePastesRef.current.get(requestId);
+ if (!batch || index < 0 || index >= batch.expectedCount || batch.settledIndexes.has(index)) return;
+ batch.settledIndexes.add(index);
+ if (uri) batch.urisByIndex.set(index, uri);
+ drainCompletedImagePastes();
+ }, [drainCompletedImagePastes]);
+
+ const commitPlainTextPaste = useCallback(async (
+ message: Extract<ComposerWebMessage, { type: 'paste-text-request' }>,
+ ) => {
+ let text = message.text ?? '';
+ if (!text) {
+ try {
+ text = await Clipboard.getStringAsync();
+ } catch {
+ text = '';
+ }
+ }
+ const nodes = composerNodesForBoundedPlainTextPaste(text);
+ if (!nodes) {
+ inject(
+ `window.cindyComposer.commitPaste(${JSON.stringify(message.requestId)}, []);`,
+ );
+ return;
+ }
+ inject(
+ `window.cindyComposer.commitPaste(${JSON.stringify(message.requestId)}, ${JSON.stringify(nodes)});`,
+ );
+ if (!resolveSessionLinkLabel) return;
+ const hrefs = new Set(nodes.flatMap((node) => (
+ node.type === 'session-link' && node.titled !== true ? [node.href] : []
+ )));
+ hrefs.forEach((href) => {
+ void resolveSessionLinkLabel(href)
+ .then((semantic) => {
+ if (!semantic) return;
+ inject(
+ `window.cindyComposer.resolveSessionLink(${JSON.stringify(href)}, ${JSON.stringify(semantic)});`,
+ );
+ })
+ .catch(() => {
+ // Keep the stable short-id placeholder when the target is unavailable.
+ });
+ });
+ }, [inject, resolveSessionLinkLabel]);
+
+ const handleMessage = useCallback((event: WebViewMessageEvent) => {
+ const message = parseComposerWebMessage(event.nativeEvent.data);
+ if (!message) return;
+ if (message.type === 'ready') {
+ readyRef.current = true;
+ inject(`window.cindyComposer.setConfig(${JSON.stringify(runtimeConfig)});`);
+ const pending = pendingDocumentRef.current;
+ pendingDocumentRef.current = null;
+ if (pending) applyDocument(pending.document, pending.focusAfter);
+ const pendingNodeInsertions = pendingNodeInsertionsRef.current;
+ pendingNodeInsertionsRef.current = [];
+ for (const node of pendingNodeInsertions) {
+ inject(`window.cindyComposer.insertNode(${JSON.stringify(node)});`);
+ }
+ if (pendingFocusRef.current) {
+ pendingFocusRef.current = false;
+ focusEditor();
+ }
+ return;
+ }
+ if (message.type === 'change') {
+ const next = parseStoredComposerDocument(message.document);
+ if (!next) return;
+ const normalized = normalizeComposerDocument(next);
+ webSignatureRef.current = JSON.stringify(normalized);
+ onChangeDocument(normalized);
+ return;
+ }
+ if (message.type === 'height') {
+ if (Number.isFinite(message.height)) onHeightChange?.(Math.max(28, Math.min(maxHeight, message.height)));
+ return;
+ }
+ if (message.type === 'focus') return onFocus?.();
+ if (message.type === 'blur') return onBlur?.();
+ if (message.type === 'paste-text-request') {
+ void commitPlainTextPaste(message);
+ return;
+ }
+ if (message.type === 'paste-images-start') {
+ pendingImagePastesRef.current.set(message.requestId, {
+ expectedCount: message.count,
+ settledIndexes: new Set(),
+ urisByIndex: new Map(),
+ });
+ pendingImagePasteOrderRef.current.push(message.requestId);
+ onPasteImagesLoading?.(Math.max(0, message.count));
+ return;
+ }
+ if (message.type === 'paste-image-failed') {
+ settlePastedImage(message.requestId, message.index);
+ return;
+ }
+ if (message.type === 'paste-image') {
+ void persistPastedImage(message)
+ .then((uri) => settlePastedImage(message.requestId, message.index, uri))
+ .catch(() => settlePastedImage(message.requestId, message.index));
+ }
+ }, [applyDocument, commitPlainTextPaste, focusEditor, inject, maxHeight, onBlur, onChangeDocument, onFocus, onHeightChange, onPasteImagesLoading, persistPastedImage, runtimeConfig, settlePastedImage]);
+
+ return (
+ <WebView
+ ref={webViewRef}
+ accessibilityHint={accessibilityHint}
+ accessibilityLabel={accessibilityLabel}
+ allowFileAccess={false}
+ javaScriptEnabled
+ keyboardDisplayRequiresUserAction={false}
+ onMessage={handleMessage}
+ originWhitelist={['about:blank']}
+ scrollEnabled={false}
+ setSupportMultipleWindows={false}
+ source={{ html }}
+ style={[styles.webView, { height, opacity: hidden ? 0 : 1 }]}
+ testID={testID}
+ textInteractionEnabled
+ />
+ );
+ },
+);
+
+function extensionForMime(mimeType: string): string {
+ if (mimeType === 'image/png') return 'png';
+ if (mimeType === 'image/gif') return 'gif';
+ if (mimeType === 'image/webp') return 'webp';
+ if (mimeType === 'image/heic' || mimeType === 'image/heif') return 'heic';
+ return 'jpg';
+}
+
+async function deleteComposerPastedImageUris(uris: readonly string[]): Promise<void> {
+ const FileSystem = await import('expo-file-system/legacy');
+ await Promise.all(uris.map((uri) => (
+ FileSystem.deleteAsync(uri, { idempotent: true }).catch(() => undefined)
+ )));
+}
+
+const styles = StyleSheet.create({
+ webView: {
+ backgroundColor: 'transparent',
+ // react-native-webview defaults the native child to flex: 1. Override it
+ // because this composer drives the child with an explicit measured height.
+ flex: 0,
+ minHeight: 28,
+ },
+});
diff --git a/apps/mobile/src/session/InlineQuoteChip.tsx b/apps/mobile/src/session/InlineQuoteChip.tsx
new file mode 100644
index 0000000000..df89b39084
--- /dev/null
+++ b/apps/mobile/src/session/InlineQuoteChip.tsx
@@ -0,0 +1,25 @@
+import { Alert } from 'react-native';
+import { MessageSquareQuote } from 'lucide-react-native';
+import { quoteSourceDisplayLabel, type ChatQuote } from '@cindy/maker-shared/chat-quotes';
+import { InlineReferenceChip } from '@/session/InlineReferenceChip';
+import { iconSize, iconStroke, useTheme } from '@/theme';
+
+export function compactQuoteLabel(text: string): string {
+ return text.replace(/\s+/g, ' ').trim();
+}
+
+/** One quote per chip, shared geometry with message-anchor references. */
+export function InlineQuoteChip({ quote }: { quote: ChatQuote }) {
+ const { colors } = useTheme();
+ const source = quoteSourceDisplayLabel(quote);
+ const label = compactQuoteLabel(quote.text);
+ return (
+ <InlineReferenceChip
+ accessibilityLabel={quote.text}
+ icon={<MessageSquareQuote color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />}
+ label={label}
+ onPress={() => Alert.alert('引用', [`“${quote.text}”`, source].filter(Boolean).join('\n\n'))}
+ testID="message.quoteChip"
+ />
+ );
+}
diff --git a/apps/mobile/src/session/InlineReferenceChip.tsx b/apps/mobile/src/session/InlineReferenceChip.tsx
new file mode 100644
index 0000000000..17172348d4
--- /dev/null
+++ b/apps/mobile/src/session/InlineReferenceChip.tsx
@@ -0,0 +1,65 @@
+import type { ReactNode } from 'react';
+import { Pressable, StyleSheet, View } from 'react-native';
+import { Text } from '@/components/AppText';
+import { fontWeight, lineHeight, radius, spacing, typeScale, useThemedStyles, type ThemeColors } from '@/theme';
+
+/** Shared compact pill shell for composer-adjacent and sent-message references. */
+export function InlineReferenceChip({
+ accessibilityLabel,
+ icon,
+ label,
+ onPress,
+ testID,
+}: {
+ accessibilityLabel?: string;
+ icon?: ReactNode;
+ label: string;
+ onPress?: () => void;
+ testID?: string;
+}) {
+ const styles = useThemedStyles(makeStyles);
+ const content = (
+ <>
+ {icon ? <View style={styles.icon}>{icon}</View> : null}
+ <Text numberOfLines={1} style={styles.label}>{label}</Text>
+ </>
+ );
+ if (!onPress) return <View style={styles.pill} testID={testID}>{content}</View>;
+ return (
+ <Pressable
+ accessibilityLabel={accessibilityLabel ?? label}
+ accessibilityRole="button"
+ hitSlop={8}
+ onPress={onPress}
+ style={({ pressed }) => [styles.pill, pressed && styles.pressed]}
+ testID={testID}
+ >
+ {content}
+ </Pressable>
+ );
+}
+
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ pill: {
+ alignItems: 'center',
+ alignSelf: 'flex-start',
+ backgroundColor: colors.surfaceChip,
+ borderColor: colors.border,
+ borderRadius: radius.pill,
+ borderWidth: StyleSheet.hairlineWidth,
+ flexDirection: 'row',
+ gap: 6,
+ maxWidth: 240,
+ paddingHorizontal: spacing.sm,
+ paddingVertical: 2,
+ },
+ icon: { alignItems: 'center', justifyContent: 'center' },
+ label: {
+ color: colors.textPrimary,
+ flexShrink: 1,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.code,
+ },
+ pressed: { opacity: 0.7 },
+});
diff --git a/apps/mobile/src/session/MessageActionSheet.tsx b/apps/mobile/src/session/MessageActionSheet.tsx
new file mode 100644
index 0000000000..c4ddad1311
--- /dev/null
+++ b/apps/mobile/src/session/MessageActionSheet.tsx
@@ -0,0 +1,153 @@
+import { useCallback, useEffect, useRef } from 'react';
+import { Pressable, StyleSheet, View } from 'react-native';
+import {
+ Link2,
+ MessageSquarePlus,
+ Split,
+ Trash2,
+ Undo2,
+ type LucideIcon,
+} from 'lucide-react-native';
+import { useSafeAreaInsets } from 'react-native-safe-area-context';
+import { Text } from '@/components/AppText';
+import { BlurBackdrop } from '@/session/BlurBackdrop';
+import { SheetModal } from '@/session/SheetModal';
+import type { MobileMessageMenuActionId, MobileMessageMenuItem } from '@/session/messageActionMenu';
+import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
+
+const ACTION_ICONS: Record<MobileMessageMenuActionId, LucideIcon> = {
+ fork: Split,
+ 'add-to-chat': MessageSquarePlus,
+ 'copy-link': Link2,
+ rewind: Undo2,
+ delete: Trash2,
+};
+
+/** Touch-first counterpart of desktop's compact More dropdown. */
+export function MessageActionSheet({
+ items,
+ onAction,
+ onClose,
+ visible,
+}: {
+ items: readonly MobileMessageMenuItem[];
+ onAction(action: MobileMessageMenuActionId): void;
+ onClose(): void;
+ visible: boolean;
+}) {
+ const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
+ const insets = useSafeAreaInsets();
+ const pendingActionRef = useRef<MobileMessageMenuActionId | null>(null);
+
+ // A fade-out interrupted by a quick reopen must not replay the old choice
+ // when the later close eventually finishes.
+ useEffect(() => {
+ if (visible) pendingActionRef.current = null;
+ }, [visible]);
+ const handleClosed = useCallback(() => {
+ const action = pendingActionRef.current;
+ pendingActionRef.current = null;
+ if (action) onAction(action);
+ }, [onAction]);
+ const closeWithoutAction = useCallback(() => {
+ pendingActionRef.current = null;
+ onClose();
+ }, [onClose]);
+
+ const select = (action: MobileMessageMenuActionId) => {
+ pendingActionRef.current = action;
+ onClose();
+ };
+
+ return (
+ <SheetModal
+ backdropTestID="message.actions.backdrop"
+ onBackdropPress={closeWithoutAction}
+ onClosed={handleClosed}
+ onRequestClose={closeWithoutAction}
+ visible={visible}
+ >
+ <View style={[styles.cardArea, { paddingBottom: Math.max(insets.bottom, spacing.md) }]}>
+ <View style={styles.actionCard} testID="message.actions.sheet">
+ <BlurBackdrop intensity={32} overlayColor={colors.sheetActionSurface} />
+ {items.map((item) => {
+ const Icon = ACTION_ICONS[item.id];
+ const color = item.destructive ? colors.destructive : colors.sheetActionText;
+ return (
+ <View key={item.id}>
+ {item.separatorBefore ? <View style={styles.separator} /> : null}
+ <Pressable
+ accessibilityLabel={item.label}
+ accessibilityRole="button"
+ onPress={() => select(item.id)}
+ style={({ pressed }) => [styles.actionRow, pressed && styles.pressed]}
+ testID={`message.actions.${item.id}`}
+ >
+ <Icon color={color} size={iconSize.lg} strokeWidth={iconStroke.regular} />
+ <Text numberOfLines={1} style={[styles.actionLabel, item.destructive && styles.danger]}>
+ {item.label}
+ </Text>
+ </Pressable>
+ </View>
+ );
+ })}
+ </View>
+ <Pressable
+ accessibilityLabel="取消"
+ accessibilityRole="button"
+ onPress={closeWithoutAction}
+ style={({ pressed }) => [styles.cancelCard, pressed && styles.pressed]}
+ testID="message.actions.cancel"
+ >
+ <BlurBackdrop intensity={32} overlayColor={colors.sheetActionSurface} />
+ <Text style={styles.cancelText}>取消</Text>
+ </Pressable>
+ </View>
+ </SheetModal>
+ );
+}
+
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ cardArea: { gap: spacing.sm, paddingHorizontal: spacing.md },
+ actionCard: {
+ backgroundColor: 'transparent',
+ borderColor: colors.sheetActionBorder,
+ borderRadius: radius.container,
+ borderWidth: StyleSheet.hairlineWidth,
+ overflow: 'hidden',
+ },
+ actionRow: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: spacing.md,
+ minHeight: 54,
+ paddingHorizontal: spacing.lg,
+ },
+ separator: { backgroundColor: colors.sheetActionBorder, height: StyleSheet.hairlineWidth },
+ actionLabel: {
+ color: colors.sheetActionText,
+ flexShrink: 1,
+ fontSize: typeScale.listBody,
+ fontWeight: fontWeight.semibold,
+ lineHeight: lineHeight.listBody,
+ },
+ danger: { color: colors.destructive },
+ cancelCard: {
+ alignItems: 'center',
+ backgroundColor: 'transparent',
+ borderColor: colors.sheetActionBorder,
+ borderRadius: radius.container,
+ borderWidth: StyleSheet.hairlineWidth,
+ justifyContent: 'center',
+ minHeight: 54,
+ overflow: 'hidden',
+ },
+ cancelText: {
+ color: colors.sheetActionText,
+ fontSize: typeScale.listBody,
+ fontWeight: fontWeight.semibold,
+ lineHeight: lineHeight.listBody,
+ },
+ pressed: { opacity: 0.72 },
+});
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index b37bebc5a2..eb7fa15b05 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -12,8 +12,10 @@ import {
CircleDashed,
CircleStop,
Copy,
+ Ellipsis,
ExternalLink,
File as FileIcon,
+ FileText,
Layers,
ListTodo,
LoaderCircle,
@@ -65,6 +67,19 @@ import { QuoteCapsule } from '@/session/QuoteCapsule';
import { StreamingStatusText } from '@/session/StreamingStatusText';
import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
import { motionDuration, motionEasing } from '@/theme/tokens';
+import { MessageActionSheet } from '@/session/MessageActionSheet';
+import { buildMobileMessageMenu, type MobileMessageMenuActionId } from '@/session/messageActionMenu';
+import { InlineQuoteChip } from '@/session/InlineQuoteChip';
+import { InlineReferenceChip } from '@/session/InlineReferenceChip';
+import {
+ composerDocumentFromSerializedMessage,
+ type ComposerDocument,
+} from '@/session/composerDocument';
+import {
+ buildVisibleSentInlineTokens,
+ sentInlineTokensDisplayText,
+ type SentInlineToken,
+} from '@/session/sentMessageAtoms';
import {
SELECTION_QUOTE_MENU_LABEL,
SelectionQuoteContext,
@@ -88,6 +103,7 @@ import {
buildFilePayload,
buildMediaPayload,
buildMermaidPayload,
+ buildTextPayload,
buildToolResultPayload,
formatDiffPayloadView,
payloadMediaKindLabel,
@@ -140,6 +156,7 @@ import {
mobileMarkdownImageUrlForWorkdir,
mobileMarkdownInlineImageSize,
parseMobileMarkdown,
+ parseMobileMarkdownInlines,
type MobileMarkdownBlockGroup,
type MobileMarkdownInline,
} from '@/session/messageMarkdown';
@@ -150,6 +167,7 @@ import {
parseSessionDeepLinkUrl,
projectDisplayName,
shortSessionId,
+ type SessionDeepLinkTarget,
} from '@/session/sessionLinks';
import {
formatMobileSessionReferenceMetadata,
@@ -170,7 +188,14 @@ import {
verifyRemotePathCached,
type RemotePathVerdict,
} from '@/session/remotePathVerdict';
-import { useRemoteSessions } from '@/session/remoteSessionStore';
+import {
+ useRemoteSessionMessages,
+ useRemoteSessions,
+} from '@/session/remoteSessionStore';
+import {
+ compactSessionMessageLabel,
+ mobileSessionMessageDisplayText,
+} from '@/session/sessionMessageText';
import { buildMobileMarkdownTableColumnWidths } from '@/session/messageTableLayout';
import { buildPayloadHeaderLayout, buildPayloadModalSafeArea } from '@/session/payloadHeaderLayout';
import { buildPayloadBodyLayout, type PayloadBodyLayout } from '@/session/payloadBodyLayout';
@@ -379,6 +404,7 @@ function MarkdownSelectableSpan(props: ComponentProps<typeof Text>) {
/** Composer-ready user message body with product quotes kept out of raw text. */
export interface MobileMessageDraft {
+ document: ComposerDocument;
text: string;
quotes: readonly ChatQuote[];
/** marker 不进入可见输入框;未编辑时用这份原文保证 quote / prose 顺序不变。 */
@@ -388,6 +414,8 @@ export interface MobileMessageDraft {
interface MessageActions {
/** 长按/操作条「复制消息链接」:复制该消息的会话深链(带 ?message= 锚点)。 */
onCopyMessageLink?: (clientId: string) => void;
+ /** Insert this message's anchored link as an atom in the active composer. */
+ onAddMessageToComposer?: (clientId: string) => void;
/**
* chat-text-quote:选中消息文字 → 系统选择菜单「添加到对话」项的采集回调
* (会话页写入 chatQuoteStore)。未传时选区采集整体关闭(context 为 null,
@@ -419,6 +447,7 @@ export function MessageRenderer({
followLatestRequestKey,
items,
onCopyMessageLink,
+ onAddMessageToComposer,
onForkMessage,
onDeleteMessage,
onLoadEarlier,
@@ -655,6 +684,7 @@ export function MessageRenderer({
visibleMessageCount: listData.length,
});
const actions: MessageActions & { firstUserMessageClientId?: string } = useMemo(() => ({
+ onAddMessageToComposer,
onCopyMessageLink,
onForkMessage,
onDeleteMessage,
@@ -672,6 +702,7 @@ export function MessageRenderer({
firstUserMessageClientId,
isSessionStreaming,
onCopyMessageLink,
+ onAddMessageToComposer,
onDeleteMessage,
onForkMessage,
onOpenForkOrigin,
@@ -1408,13 +1439,14 @@ function MessageBubble({
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
const [copyState, setCopyState] = useState<CopyMessageStatus | 'idle' | 'copying'>('idle');
+ const [actionSheetOpen, setActionSheetOpen] = useState(false);
// chat-text-quote:只解析持久化 quotesEncoded 明确标记的产品引用消息,避免
// 把用户手写的 Markdown blockquote 误当产品引用。兼容 desktop 的交错
// marker 块和 mobile 的前置引用。旧 markerless 消息保持 leading-only,
- // 避免把正文里的用户 Markdown blockquote 误当产品引用。手机版仍把引用聚合成
- // 「N 处引用」胶囊,但正文不再泄露内部 marker/source 行。copy / rewind /
- // fork 额外携带完整 ordered body,在可见草稿未编辑时无损重发。orca 协同
- // 消息已走 orcaCard 分支,不进本路径。
+ // 避免把正文里的用户 Markdown blockquote 误当产品引用。手机版逐条渲染紧凑
+ // quote chip,正文不泄露内部 marker/source 行;fork / rewind 直接携带完整
+ // ComposerDocument,无损恢复 quote、pasted-text 与 Slash。orca 协同消息已走
+ // orcaCard 分支,不进本路径。
const quoteSegments = useMemo(
() => (item.message.kind === 'user'
&& item.message.quotesEncoded === true
@@ -1435,10 +1467,52 @@ function MessageBubble({
const bubbleBody = messageQuotes.length > 0
? joinChatQuoteTextSegments(quoteSegments)
: item.message.body;
+ const sentInlineTokens = useMemo(
+ () => (item.message.kind === 'user'
+ ? buildVisibleSentInlineTokens(
+ item.message.body,
+ quoteSegments.length > 0
+ ? quoteSegments
+ : item.message.body ? [{ kind: 'text' as const, text: item.message.body }] : [],
+ item.message.pastedTextRanges,
+ item.message.slashCommandRanges,
+ )
+ : []),
+ [
+ item.message.body,
+ item.message.kind,
+ item.message.pastedTextRanges,
+ item.message.slashCommandRanges,
+ quoteSegments,
+ ],
+ );
+ const hasSentInlineAtoms = sentInlineTokens.some((token) => token.kind !== 'text');
+ const rendersSentInlineBody = hasSentInlineAtoms;
+ const displayBubbleBody = hasSentInlineAtoms
+ ? sentInlineTokensDisplayText(sentInlineTokens)
+ : bubbleBody;
+ const composerDraftDocument = useMemo(
+ () => (item.message.kind === 'user'
+ ? composerDocumentFromSerializedMessage(item.message.body, {
+ quotesEncoded: item.message.quotesEncoded,
+ agentReferences: item.message.agentReferences,
+ pastedTextRanges: item.message.pastedTextRanges,
+ slashCommandRanges: item.message.slashCommandRanges,
+ })
+ : null),
+ [
+ item.message.body,
+ item.message.agentReferences,
+ item.message.kind,
+ item.message.pastedTextRanges,
+ item.message.quotesEncoded,
+ item.message.slashCommandRanges,
+ ],
+ );
const presentation = summarizeMessageBubblePresentation({
align: item.message.align,
attachmentCount: item.message.attachments?.length ?? 0,
- body: bubbleBody,
+ body: displayBubbleBody,
hasSystemCard: !!item.message.systemCardType,
isStreaming: item.message.isStreaming,
kind: item.message.kind,
@@ -1485,7 +1559,8 @@ function MessageBubble({
&& actions.isSessionStreaming !== true
&& (item.message.kind === 'user' || item.message.kind === 'assistant')
);
- const canCopyLink = !!(canUseCompletedActions && clientId && actions.onCopyMessageLink);
+ const canCopyLink = !!(showCompletedActionBar && clientId && actions.onCopyMessageLink);
+ const canAddToChat = !!(showCompletedActionBar && clientId && actions.onAddMessageToComposer);
const contentLayout = useMemo(() => buildMessageContentLayout({
screenWidth: actions.screenWidth,
}), [actions.screenWidth]);
@@ -1508,14 +1583,14 @@ function MessageBubble({
const collapseMeasureEnabled = (isUser || hookSource !== undefined)
&& (item.message.kind === 'user' || hookSource !== undefined)
&& !item.message.systemCardType
- && !!bubbleBody
- && mayExceedVisualLineThreshold(bubbleBody, collapseThreshold);
+ && !!displayBubbleBody
+ && mayExceedVisualLineThreshold(displayBubbleBody, collapseThreshold);
// 实测行数与被测 body 绑定存储:FlatList 复用组件实例时 body 可能原地变化
// (服务端同步补丁等),旧实测值若不随内容失效,会在下一次 onTextLayout 到达
// 前产生"过期行数"的错误收起判定;body 不匹配时视为未测量,回落估算兜底。
const [measuredBody, setMeasuredBody] = useState<{ body: string; lines: number } | null>(null);
const measuredBodyLines =
- measuredBody && measuredBody.body === bubbleBody ? measuredBody.lines : null;
+ measuredBody && measuredBody.body === displayBubbleBody ? measuredBody.lines : null;
const [longMessageExpanded, setLongMessageExpanded] = useState(false);
// 折叠判定单向闩锁(绑定 body,FlatList 复用换消息时自动失效):测量 Text
// 的排版宽度跟随气泡宽度,而气泡宽度又随折叠状态变化(展开态的 markdown
@@ -1525,24 +1600,29 @@ function MessageBubble({
// 收起」的判定只进不出:后续宽度变化跌回阈值以下不再自动展开;用户手动
// 点「展开」走 longMessageExpanded,不受闩锁影响。
const [collapseLatchBody, setCollapseLatchBody] = useState<string | null>(null);
- const collapseLatched = collapseLatchBody === bubbleBody;
+ const collapseLatched = collapseLatchBody === displayBubbleBody;
const collapseResolved = collapseMeasureEnabled
- && resolveUserMessageCollapse(bubbleBody, measuredBodyLines, collapseThreshold);
+ && resolveUserMessageCollapse(displayBubbleBody, measuredBodyLines, collapseThreshold);
useEffect(() => {
- if (collapseResolved && !collapseLatched) setCollapseLatchBody(bubbleBody);
- }, [collapseResolved, collapseLatched, bubbleBody]);
+ if (collapseResolved && !collapseLatched) setCollapseLatchBody(displayBubbleBody);
+ }, [collapseResolved, collapseLatched, displayBubbleBody]);
const shouldCollapseLongMessage = (collapseMeasureEnabled && collapseLatched) || collapseResolved;
const longMessageCollapsed = shouldCollapseLongMessage && !longMessageExpanded;
- const actionBar = useMemo(() => buildMessageActionBarPresentation({
- align: isUser ? 'user' : 'agent',
- canCopy,
+ const messageMenu = useMemo(() => buildMobileMessageMenu({
+ canAddToChat,
+ canCopyLink,
canDelete,
canFork,
canRewind,
+ }), [canAddToChat, canCopyLink, canDelete, canFork, canRewind]);
+ const actionBar = useMemo(() => buildMessageActionBarPresentation({
+ align: isUser ? 'user' : 'agent',
+ canCopy,
+ hasMoreActions: messageMenu.length > 0,
hasTime: !!relativeTime,
hasTurnCost: !!turnCost,
isStreaming: isStreamingAssistant,
- }), [canCopy, canDelete, canFork, canRewind, isStreamingAssistant, isUser, relativeTime, turnCost]);
+ }), [canCopy, isStreamingAssistant, isUser, messageMenu.length, relativeTime, turnCost]);
const hasActions = actionBar.items.length > 0;
const actionBusy = !!clientId && actions.busyClientId === clientId;
const disabled = !!actions.busyClientId;
@@ -1553,14 +1633,6 @@ function MessageBubble({
return () => clearTimeout(timer);
}, [copyState]);
- // 复制消息链接的 Check 反馈,独立于 copyState(两个按钮互不串信号)。
- const [linkCopyState, setLinkCopyState] = useState<'idle' | 'copied'>('idle');
- useEffect(() => {
- if (linkCopyState === 'idle') return;
- const timer = setTimeout(() => setLinkCopyState('idle'), 1500);
- return () => clearTimeout(timer);
- }, [linkCopyState]);
-
const copyMessage = useCallback(() => {
if (!canCopy || copyState === 'copying') return;
setCopyState('copying');
@@ -1573,6 +1645,7 @@ function MessageBubble({
}
if (id === 'rewind' && clientId) {
actions.onPreviewRewind?.(clientId, {
+ document: composerDraftDocument ?? composerDocumentFromSerializedMessage(item.message.body),
text: bubbleBody,
quotes: messageQuotes,
...(item.message.quotesEncoded === true ? { orderedBody: item.message.body } : {}),
@@ -1584,6 +1657,7 @@ function MessageBubble({
clientId,
item.message.kind === 'user'
? {
+ document: composerDraftDocument ?? composerDocumentFromSerializedMessage(item.message.body),
text: bubbleBody,
quotes: messageQuotes,
...(item.message.quotesEncoded === true ? { orderedBody: item.message.body } : {}),
@@ -1599,27 +1673,30 @@ function MessageBubble({
actions,
bubbleBody,
clientId,
+ composerDraftDocument,
copyMessage,
item.message.body,
item.message.kind,
item.message.quotesEncoded,
messageQuotes,
]);
- // 时间文本兼任「复制消息链接」入口:点按复制该消息的会话深链(带 ?message=
- // 锚点),复制成功后短暂换成「链接已复制」。不单独占一个操作按钮位。
+ const selectMenuAction = useCallback((id: MobileMessageMenuActionId) => {
+ if (!clientId) return;
+ if (id === 'fork') return selectControlAction('fork');
+ if (id === 'rewind') return selectControlAction('rewind');
+ if (id === 'delete') return selectControlAction('delete');
+ if (id === 'add-to-chat') return actions.onAddMessageToComposer?.(clientId);
+ actions.onCopyMessageLink?.(clientId);
+ }, [actions, clientId, selectControlAction]);
+ // 时间只展示发送时间;消息锚点复制移入语义明确的 More 菜单。
const timeText = relativeTime ? (
<Text
- accessibilityHint={canCopyLink ? '点按复制消息链接' : undefined}
accessibilityLabel={absoluteTime ? `发送时间 ${absoluteTime}` : undefined}
key="time"
- onPress={canCopyLink && clientId ? () => {
- actions.onCopyMessageLink?.(clientId);
- setLinkCopyState('copied');
- } : undefined}
style={styles.messageActionMeta}
testID="message.timeText"
>
- {linkCopyState === 'copied' ? '链接已复制' : relativeTime}
+ {relativeTime}
</Text>
) : null;
const costText = turnCost ? (
@@ -1653,7 +1730,7 @@ function MessageBubble({
/>
) : null;
const hasBubbleContent = !!(
- item.message.systemCardType || bubbleBody || item.message.secondaryBody
+ item.message.systemCardType || displayBubbleBody || item.message.secondaryBody
);
// 气泡是纯 View,不承接任何手势:文本选择走正文原生 Text selectable(长按文字就地选择复制),
// 气泡上不能挂 Pressable——它会参与触摸协商,干扰正文里表格/代码块横向 ScrollView 的拖动。
@@ -1686,7 +1763,7 @@ function MessageBubble({
data={item.message.systemCardData}
type={item.message.systemCardType}
/>
- ) : bubbleBody ? (
+ ) : displayBubbleBody ? (
longMessageCollapsed ? (
// 收起态降级为纯文本(对齐桌面:被裁切的富文本节点不该保留交互),
// 展开后恢复 MarkdownBody 的完整渲染。文本选择不因收起而丢失:
@@ -1698,8 +1775,18 @@ function MessageBubble({
style={styles.messageText}
testID="message.collapsedBody"
>
- {bubbleBody}
+ {displayBubbleBody}
</MarkdownSelectableText>
+ ) : rendersSentInlineBody ? (
+ <SentInlineAtomBody
+ layout={contentLayout}
+ markdownImageCacheKey={item.message.key}
+ onOpenPayload={actions.onOpenPayload}
+ onOpenSessionLink={actions.onOpenSessionLink}
+ selectable={canSelectVisibleText}
+ sessionReferences={item.message.sessionReferences}
+ tokens={sentInlineTokens}
+ />
) : (
<MarkdownBody
allowIosUITextView={!shouldCollapseLongMessage}
@@ -1734,12 +1821,12 @@ function MessageBubble({
<Text
numberOfLines={collapseThreshold + 1}
onTextLayout={(e) => setMeasuredBody({
- body: bubbleBody,
+ body: displayBubbleBody,
lines: e.nativeEvent.lines.length,
})}
style={styles.messageText}
>
- {bubbleBody}
+ {displayBubbleBody}
</Text>
</View>
) : null}
@@ -1785,10 +1872,6 @@ function MessageBubble({
</Text>
</View>
) : null}
- {messageQuotes.length > 0 ? (
- // chat-text-quote:气泡上方渲「N 处引用」胶囊(右对齐),点按展开逐条预览。
- <QuoteCapsule quotes={messageQuotes} testIDPrefix="message.quoteCapsule" variant="bubble" />
- ) : null}
{attachmentStripNode}
{hasBubbleContent || (!attachmentStripNode && messageQuotes.length === 0) ? bubble : null}
{item.message.kind === 'assistant' && item.message.modelMismatch ? (
@@ -1813,6 +1896,17 @@ function MessageBubble({
if (id === 'streaming') return <View key="streaming">{streamingStatus}</View>;
if (id === 'time') return timeText;
if (id === 'cost') return costText;
+ if (id === 'more') {
+ return (
+ <MessageMoreButton
+ buttonSize={actionBar.buttonSize}
+ disabled={disabled || actionBusy}
+ iconSize={actionBar.iconSize}
+ key="more"
+ onPress={() => setActionSheetOpen(true)}
+ />
+ );
+ }
if (isMessageControlActionId(id)) {
return (
<MessageControlButton
@@ -1830,6 +1924,12 @@ function MessageBubble({
})}
</View>
) : null}
+ <MessageActionSheet
+ items={messageMenu}
+ onAction={selectMenuAction}
+ onClose={() => setActionSheetOpen(false)}
+ visible={actionSheetOpen}
+ />
</View>
);
}
@@ -2936,6 +3036,80 @@ function OrcaCollabCard({ card, screenWidth }: { card: OrcaCollabCardModel; scre
// 消息正文统一走原生 markdown 渲染(流式与完成态同一条路径,完成时无"原生→WebView"的切换跳变)。
// 文本选择 = 完成态消息的各块 Text 原生 selectable:长按文字就地弹系统选择手柄/Copy 菜单,
// 不跳转界面;整条复制走操作条按钮。选择按块进行(原生 Text 能力边界,跨段选择做不到)。
+/** Sent user atoms stay compact while their full wire text remains copyable/sendable. */
+function SentInlineAtomBody({
+ layout,
+ markdownImageCacheKey,
+ onOpenPayload,
+ onOpenSessionLink,
+ selectable,
+ sessionReferences,
+ tokens,
+}: {
+ layout: MessageContentLayout;
+ markdownImageCacheKey?: string;
+ onOpenPayload?: (payload: MessagePayload) => void;
+ onOpenSessionLink?: (url: string) => void;
+ selectable: boolean;
+ sessionReferences?: readonly MobilePersistedSessionReferenceMetadata[];
+ tokens: readonly SentInlineToken[];
+}) {
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ return (
+ <View style={styles.sentInlineAtomBody} testID="message.sentInlineAtoms">
+ {tokens.map((token, index) => {
+ if (token.kind === 'quote') {
+ return (
+ <InlineQuoteChip
+ key={`quote:${token.quote.sourcePath ?? 'chat'}:${index}:${token.quote.text}`}
+ quote={token.quote}
+ />
+ );
+ }
+ if (token.kind === 'pasted') {
+ return (
+ <InlineReferenceChip
+ accessibilityLabel={token.display}
+ icon={<FileText color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />}
+ key={`pasted:${index}`}
+ label={token.display}
+ onPress={onOpenPayload
+ ? () => onOpenPayload(buildTextPayload('Pasted text', token.text))
+ : undefined}
+ testID="message.pastedTextChip"
+ />
+ );
+ }
+ if (token.kind === 'slash') {
+ return (
+ <InlineReferenceChip
+ accessibilityLabel={token.text}
+ key={`slash:${index}`}
+ label={token.text}
+ testID="message.slashCommandChip"
+ />
+ );
+ }
+ return token.text ? (
+ <View key={`text:${index}`} style={styles.sentInlineTextChunk}>
+ <MarkdownBody
+ layout={layout}
+ markdownImageCacheKey={markdownImageCacheKey}
+ onOpenPayload={onOpenPayload}
+ onOpenSessionLink={onOpenSessionLink}
+ selectable={selectable}
+ sessionReferences={sessionReferences}
+ streaming={false}
+ text={token.text}
+ />
+ </View>
+ ) : null;
+ })}
+ </View>
+ );
+}
+
function MarkdownBody({
allowIosUITextView = true,
markdownImageCacheKey,
@@ -3443,6 +3617,7 @@ function renderInline(
/** text_run 合并树里多个块共父,key 需要块级前缀防冲突。 */
keyPrefix?: string;
onOpenImage?: (url: string, alt?: string) => void;
+ onOpenPayload?: (payload: MessagePayload) => void;
onOpenSessionLink?: (url: string) => void;
sessionReferenceDetails?: Readonly<Record<string, string>>;
sessionLinkTitles?: Readonly<Record<string, string>>;
@@ -3453,6 +3628,15 @@ function renderInline(
} = {},
): ReactNode {
const SpanText = ctx.SpanText ?? Text;
+ const openImage = ctx.onOpenImage ?? (ctx.onOpenPayload
+ ? (url: string, alt?: string) => {
+ const title = mobileMarkdownImageTitle(url, alt);
+ ctx.onOpenPayload?.(buildMediaPayload(
+ { kind: 'image', url, title, previewable: isMobileMarkdownImageDirectUrl(url) },
+ title,
+ ));
+ }
+ : undefined);
const spanKey = (suffix: string) => (ctx.keyPrefix ? `${ctx.keyPrefix}:${suffix}` : suffix);
switch (inline.type) {
case 'text':
@@ -3460,25 +3644,18 @@ function renderInline(
case 'link': {
const session = parseSessionDeepLinkUrl(inline.url);
if (session) {
- // 会话深链 → chip 文案(作者 label / 标题 map / 短 id 降级),app 内跳转;
- // 绝不落到 Linking.openURL(app 注册的 OS scheme 是 'xdmaker',打不开)。
- const explicit =
- inline.text.trim() && inline.text.trim() !== inline.url ? inline.text.trim() : null;
- const title =
- explicit
- ?? ctx.sessionLinkTitles?.[session.sessionId]
- ?? `会话 ${shortSessionId(session.sessionId)}`;
- const detail = ctx.sessionReferenceDetails?.[
- mobileSessionReferenceMetadataKey(session.sessionId, session.messageClientId)
- ];
return (
- <SpanText
+ <MarkdownSessionLinkSpan
+ baseStyle={ctx.baseStyle}
+ inline={inline}
key={spanKey(`session-link:${index}:${inline.url}`)}
- onPress={ctx.onOpenSessionLink ? () => ctx.onOpenSessionLink?.(inline.url) : undefined}
- style={[ctx.baseStyle, styles.markdownLink, styles.sessionLinkChipText]}
- >
- {`› ${title}${detail ? ` · ${detail}` : ''}`}
- </SpanText>
+ onOpenSessionLink={ctx.onOpenSessionLink}
+ session={session}
+ sessionReferenceDetails={ctx.sessionReferenceDetails}
+ sessionLinkTitles={ctx.sessionLinkTitles}
+ SpanText={SpanText}
+ styles={styles}
+ />
);
}
// 非 session 的 Cindy 深链(project 等,双 scheme:cindy 主 + xdt-maker
@@ -3562,7 +3739,7 @@ function renderInline(
return (
<SpanText
key={spanKey(`image:${index}:${inline.url}`)}
- onPress={ctx.onOpenImage ? () => ctx.onOpenImage?.(inline.url, inline.alt) : undefined}
+ onPress={openImage ? () => openImage(inline.url, inline.alt) : undefined}
style={[ctx.baseStyle, styles.markdownLink]}
testID="message.markdownInlineImageChip"
>
@@ -3577,7 +3754,7 @@ function renderInline(
return (
<Text
key={`image:${index}:${inline.url}`}
- onPress={ctx.onOpenImage ? () => ctx.onOpenImage?.(inline.url, inline.alt) : undefined}
+ onPress={openImage ? () => openImage(inline.url, inline.alt) : undefined}
testID="message.markdownInlineImage"
>
<View style={size}>
@@ -3594,6 +3771,52 @@ function renderInline(
}
}
+function MarkdownSessionLinkSpan({
+ baseStyle,
+ inline,
+ onOpenSessionLink,
+ session,
+ sessionReferenceDetails,
+ sessionLinkTitles,
+ SpanText,
+ styles,
+}: {
+ baseStyle?: StyleProp<TextStyle>;
+ inline: Extract<MobileMarkdownInline, { type: 'link' }>;
+ onOpenSessionLink?: (url: string) => void;
+ session: SessionDeepLinkTarget;
+ sessionReferenceDetails?: Readonly<Record<string, string>>;
+ sessionLinkTitles?: Readonly<Record<string, string>>;
+ SpanText: typeof Text;
+ styles: ReturnType<typeof makeStyles>;
+}) {
+ const messages = useRemoteSessionMessages(session.sessionId);
+ const explicit =
+ inline.text.trim() && inline.text.trim() !== inline.url ? inline.text.trim() : null;
+ const targetMessage = session.messageClientId
+ ? messages.find((message) => (
+ message.clientId === session.messageClientId || message.id === session.messageClientId
+ ))
+ : null;
+ const messageLabel = targetMessage ? mobileSessionMessageDisplayText(targetMessage) : null;
+ const title = session.messageClientId
+ ? compactSessionMessageLabel(messageLabel ?? shortSessionId(session.messageClientId))
+ : explicit
+ ?? sessionLinkTitles?.[session.sessionId]
+ ?? `会话 ${shortSessionId(session.sessionId)}`;
+ const detail = sessionReferenceDetails?.[
+ mobileSessionReferenceMetadataKey(session.sessionId, session.messageClientId)
+ ];
+ return (
+ <SpanText
+ onPress={onOpenSessionLink ? () => onOpenSessionLink(inline.url) : undefined}
+ style={[baseStyle, styles.markdownLink, styles.sessionLinkChipText]}
+ >
+ {`${session.messageClientId ? '❝' : '↳'} ${title}${detail ? ` · ${detail}` : ''}`}
+ </SpanText>
+ );
+}
+
function AttachmentStrip({
attachments,
align,
@@ -5176,8 +5399,42 @@ function MessageControlButton({
);
}
-function isMessageControlActionId(id: MessageActionBarItemId): id is MobileMessageControlActionId {
- return id === 'copy' || id === 'delete' || id === 'rewind' || id === 'fork';
+function MessageMoreButton({
+ buttonSize,
+ disabled,
+ iconSize: size,
+ onPress,
+}: {
+ buttonSize: number;
+ disabled?: boolean;
+ iconSize: number;
+ onPress(): void;
+}) {
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ return (
+ <Pressable
+ accessibilityLabel="更多消息操作"
+ accessibilityRole="button"
+ accessibilityState={{ disabled: disabled === true }}
+ disabled={disabled}
+ hitSlop={MESSAGE_CONTROL_HIT_SLOP}
+ onPress={onPress}
+ style={({ pressed }) => [
+ styles.messageIconAction,
+ { height: buttonSize, width: buttonSize },
+ pressed && styles.pressed,
+ disabled && styles.disabled,
+ ]}
+ testID="message.moreButton"
+ >
+ <Ellipsis color={colors.textSecondary} size={size} strokeWidth={iconStroke.regular} />
+ </Pressable>
+ );
+}
+
+function isMessageControlActionId(id: MessageActionBarItemId): id is 'copy' {
+ return id === 'copy';
}
function messageControlActionLabel(
@@ -5295,6 +5552,18 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
gap: 2,
width: '100%',
},
+ sentInlineAtomBody: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ flexWrap: 'wrap',
+ gap: spacing.xs,
+ maxWidth: '100%',
+ },
+ sentInlineTextChunk: {
+ flexBasis: '100%',
+ flexShrink: 1,
+ maxWidth: '100%',
+ },
userMessageItem: {
alignItems: 'flex-end',
},
diff --git a/apps/mobile/src/session/MobileComposerInputRow.tsx b/apps/mobile/src/session/MobileComposerInputRow.tsx
index 89d48dbcbf..fab3b3d09a 100644
--- a/apps/mobile/src/session/MobileComposerInputRow.tsx
+++ b/apps/mobile/src/session/MobileComposerInputRow.tsx
@@ -84,6 +84,8 @@ export interface MobileComposerInputRowProps {
* null / undefined 走内容自动增长(现状行为)。
*/
inputFrameHeight?: number | Animated.Value | null;
+ /** Rich composer replacement for the plain TextInput. */
+ inputElement?: ReactNode;
inputOverlay?: ReactNode;
inputRef?: unknown;
inputStyle?: StyleProp<TextStyle>;
@@ -155,6 +157,7 @@ export function MobileComposerInputRow({
floatingVoiceButton,
floatingVoiceButtonStyle,
inputFrameHeight,
+ inputElement,
inputOverlay,
inputRef,
inputStyle,
@@ -254,11 +257,11 @@ export function MobileComposerInputRow({
inputFrameHeight != null && { height: inputFrameHeight },
]}
>
- {onPasteImages && !isExpoGo ? (
+ {inputElement ?? (onPasteImages && !isExpoGo ? (
<TextInputWrapper onPaste={handleNativePaste} style={styles.pasteWrapper}>
{textInputElement}
</TextInputWrapper>
- ) : textInputElement}
+ ) : textInputElement)}
{inputOverlay}
</Animated.View>
{cardLayout ? null : trailing}
diff --git a/apps/mobile/src/session/composerDocument.ts b/apps/mobile/src/session/composerDocument.ts
new file mode 100644
index 0000000000..5f4249fba7
--- /dev/null
+++ b/apps/mobile/src/session/composerDocument.ts
@@ -0,0 +1,785 @@
+/**
+ * Mobile composer semantic document.
+ *
+ * Text remains directly editable. References and long pasted text are atomic
+ * nodes whose wire value is independent from the compact label shown in the
+ * editor. Keeping this module free of React/WebView code makes draft
+ * persistence, fork/rewind restoration and send serialization deterministic.
+ */
+import {
+ boundAgentReferenceText,
+ type AgentInputReference,
+} from '@cindy/maker-shared/agent-input-projection';
+import {
+ formatQuoteForSend,
+ parseChatQuoteSegments,
+ type ChatQuote,
+} from '@cindy/maker-shared/chat-quotes';
+import { serializeAtResource, type ComposerAtResourceItem } from '@cindy/maker-shared/composer-palette';
+import { parseProjectDeepLinkUrl, parseSessionDeepLinkUrl } from '@/session/sessionLinks';
+import {
+ buildSentInlineTokens,
+ locateChatQuoteTextSegmentStarts,
+ projectSentRanges,
+ type SentInlineToken,
+} from '@/session/sentMessageAtoms';
+
+export const MOBILE_LONG_PASTE_LINE_THRESHOLD = 24;
+export const MOBILE_LONG_PASTE_CHAR_THRESHOLD = 4_000;
+export const MOBILE_LONG_PASTE_MAX_CHARS = 2_000_000;
+
+export interface ComposerTextNode {
+ type: 'text';
+ text: string;
+ /** Selected slash commands are styled marks, never atomic nodes. */
+ slashCommand?: string;
+}
+
+export interface ComposerQuoteNode {
+ type: 'quote';
+ quote: ChatQuote;
+}
+
+export interface ComposerMentionNode {
+ type: 'mention';
+ kind: ComposerAtResourceItem['type'] | 'project';
+ label: string;
+ raw: string;
+ /** Project references retain their decoded semantic location beside `raw`. */
+ href?: string;
+ workingDir?: string;
+}
+
+export interface ComposerSessionLinkNode {
+ type: 'session-link';
+ href: string;
+ label: string;
+ titled?: boolean;
+ messageClientId?: string;
+ /** Readable target body; never used as the compact chip label. */
+ agentText?: string;
+ agentTextTruncated?: boolean;
+}
+
+/** Async semantic data resolved for one pasted session/message deep link. */
+export interface ResolvedSessionLinkSemantic {
+ label: string;
+ agentText?: string;
+ agentTextTruncated?: boolean;
+}
+
+export type ResolveSessionLinkSemantic = (
+ href: string,
+) => Promise<ResolvedSessionLinkSemantic | null>;
+
+export interface ComposerPastedTextNode {
+ type: 'pasted-text';
+ text: string;
+ display: string;
+}
+
+export type ComposerNode =
+ | ComposerTextNode
+ | ComposerQuoteNode
+ | ComposerMentionNode
+ | ComposerSessionLinkNode
+ | ComposerPastedTextNode;
+
+export interface ComposerDocument {
+ version: 1;
+ nodes: ComposerNode[];
+}
+
+export interface ComposerPastedTextRange {
+ start: number;
+ end: number;
+ display: string;
+}
+
+export interface ComposerSlashCommandRange {
+ start: number;
+ end: number;
+}
+
+export interface SerializedComposerDocument {
+ text: string;
+ quotesEncoded: boolean;
+ agentReferences: AgentInputReference[];
+ pastedTextRanges: ComposerPastedTextRange[];
+ slashCommandRanges: ComposerSlashCommandRange[];
+}
+
+export function emptyComposerDocument(): ComposerDocument {
+ return { version: 1, nodes: [] };
+}
+
+export function textComposerDocument(text: string): ComposerDocument {
+ return normalizeComposerDocument({
+ version: 1,
+ nodes: text ? [{ type: 'text', text }] : [],
+ });
+}
+
+/** Merge adjacent compatible text runs and discard malformed/empty nodes. */
+export function normalizeComposerDocument(document: ComposerDocument): ComposerDocument {
+ const nodes: ComposerNode[] = [];
+ for (const candidate of document.nodes) {
+ const node = normalizeNode(candidate);
+ if (!node) continue;
+ const previous = nodes.at(-1);
+ if (
+ node.type === 'text'
+ && previous?.type === 'text'
+ && previous.slashCommand === node.slashCommand
+ ) {
+ previous.text += node.text;
+ } else {
+ nodes.push(node);
+ }
+ }
+ return { version: 1, nodes };
+}
+
+/** Structural equality without depending on object property insertion order. */
+export function composerDocumentsEqual(
+ leftDocument: ComposerDocument,
+ rightDocument: ComposerDocument,
+): boolean {
+ const left = normalizeComposerDocument(leftDocument).nodes;
+ const right = normalizeComposerDocument(rightDocument).nodes;
+ if (left.length !== right.length) return false;
+ return left.every((node, index) => {
+ const candidate = right[index];
+ if (!candidate || node.type !== candidate.type) return false;
+ if (node.type === 'text' && candidate.type === 'text') {
+ return node.text === candidate.text && node.slashCommand === candidate.slashCommand;
+ }
+ if (node.type === 'quote' && candidate.type === 'quote') {
+ return node.quote.text === candidate.quote.text
+ && node.quote.sourcePath === candidate.quote.sourcePath
+ && node.quote.startLine === candidate.quote.startLine
+ && node.quote.endLine === candidate.quote.endLine;
+ }
+ if (node.type === 'mention' && candidate.type === 'mention') {
+ return node.kind === candidate.kind
+ && node.label === candidate.label
+ && node.raw === candidate.raw
+ && node.href === candidate.href
+ && node.workingDir === candidate.workingDir;
+ }
+ if (node.type === 'session-link' && candidate.type === 'session-link') {
+ return node.href === candidate.href
+ && node.label === candidate.label
+ && node.titled === candidate.titled
+ && node.messageClientId === candidate.messageClientId
+ && node.agentText === candidate.agentText
+ && node.agentTextTruncated === candidate.agentTextTruncated;
+ }
+ return node.type === 'pasted-text'
+ && candidate.type === 'pasted-text'
+ && node.text === candidate.text
+ && node.display === candidate.display;
+ });
+}
+
+/** Visible editable projection. Quote atoms intentionally contribute no text. */
+export function composerDocumentProjectedText(document: ComposerDocument): string {
+ return document.nodes.map((node) => {
+ switch (node.type) {
+ case 'text':
+ case 'pasted-text':
+ return node.text;
+ case 'mention':
+ return node.raw;
+ case 'session-link':
+ return serializeSessionLink(node);
+ case 'quote':
+ return '';
+ }
+ }).join('');
+}
+
+export function composerDocumentHasContent(document: ComposerDocument): boolean {
+ return document.nodes.some((node) => (
+ node.type === 'quote'
+ || (node.type === 'pasted-text' ? node.text.length > 0 : composerNodeWireText(node).trim().length > 0)
+ ));
+}
+
+/** Apply a plain-text producer (voice, queue restore) without discarding atoms outside its edit. */
+export function reconcileComposerProjectedText(
+ document: ComposerDocument,
+ nextText: string,
+): ComposerDocument {
+ if (!nextText) return emptyComposerDocument();
+ const previousText = composerDocumentProjectedText(document);
+ if (previousText === nextText) return document;
+ let prefix = 0;
+ while (
+ prefix < previousText.length
+ && prefix < nextText.length
+ && previousText[prefix] === nextText[prefix]
+ ) prefix += 1;
+ let suffix = 0;
+ while (
+ suffix < previousText.length - prefix
+ && suffix < nextText.length - prefix
+ && previousText[previousText.length - 1 - suffix] === nextText[nextText.length - 1 - suffix]
+ ) suffix += 1;
+ const replacement = nextText.slice(prefix, nextText.length - suffix);
+ return replaceComposerTextRange(
+ document,
+ prefix,
+ previousText.length - suffix,
+ replacement ? [{ type: 'text', text: replacement }] : [],
+ );
+}
+
+export function composerDocumentQuotes(document: ComposerDocument): ChatQuote[] {
+ return document.nodes.flatMap((node) => (node.type === 'quote' ? [node.quote] : []));
+}
+
+export function appendComposerNode(
+ document: ComposerDocument,
+ node: ComposerNode,
+): ComposerDocument {
+ return normalizeComposerDocument({ version: 1, nodes: [...document.nodes, node] });
+}
+
+export function prependComposerNodes(
+ document: ComposerDocument,
+ nodes: readonly ComposerNode[],
+): ComposerDocument {
+ return normalizeComposerDocument({ version: 1, nodes: [...nodes, ...document.nodes] });
+}
+
+export function removeComposerNode(document: ComposerDocument, index: number): ComposerDocument {
+ if (!Number.isInteger(index) || index < 0 || index >= document.nodes.length) return document;
+ return normalizeComposerDocument({
+ version: 1,
+ nodes: document.nodes.filter((_, candidate) => candidate !== index),
+ });
+}
+
+/** Replace a range in the projected wire text while preserving surrounding atoms. */
+export function replaceComposerTextRange(
+ document: ComposerDocument,
+ from: number,
+ to: number,
+ replacement: readonly ComposerNode[],
+): ComposerDocument {
+ const start = Math.max(0, Math.min(from, to));
+ const end = Math.max(start, Math.max(from, to));
+ const before: ComposerNode[] = [];
+ const after: ComposerNode[] = [];
+ let offset = 0;
+
+ for (const node of document.nodes) {
+ const text = composerNodeProjectedText(node);
+ const nodeStart = offset;
+ const nodeEnd = nodeStart + text.length;
+ offset = nodeEnd;
+
+ if (nodeEnd <= start) {
+ before.push(node);
+ continue;
+ }
+ if (nodeStart >= end) {
+ after.push(node);
+ continue;
+ }
+
+ // Trigger replacement only splits editable text. Atom deletion is handled
+ // by the editor's node-selection path because quote atoms have no projected
+ // text and other atoms are never partially selectable.
+ if (node.type === 'text') {
+ const localStart = Math.max(0, start - nodeStart);
+ const localEnd = Math.min(text.length, end - nodeStart);
+ if (localStart > 0) before.push({ ...node, text: text.slice(0, localStart) });
+ if (localEnd < text.length) after.unshift({ ...node, text: text.slice(localEnd) });
+ }
+ }
+
+ if (start >= offset) before.push(...document.nodes.slice(before.length));
+ return normalizeComposerDocument({ version: 1, nodes: [...before, ...replacement, ...after] });
+}
+
+export function mentionComposerNode(
+ item: Pick<ComposerAtResourceItem, 'type' | 'relPath'> & { name?: string },
+): ComposerMentionNode {
+ return {
+ type: 'mention',
+ kind: item.type,
+ label: item.name || item.relPath,
+ raw: serializeAtResource(item),
+ };
+}
+
+export function slashCommandTextNode(commandName: string): ComposerTextNode {
+ const value = `/${commandName}`;
+ return { type: 'text', text: value, slashCommand: value };
+}
+
+export function sessionLinkComposerNode(input: {
+ href: string;
+ label: string;
+ titled?: boolean;
+ agentText?: string;
+ agentTextTruncated?: boolean;
+}): ComposerSessionLinkNode {
+ const target = parseSessionDeepLinkUrl(input.href);
+ const bounded = input.agentText ? boundAgentReferenceText(input.agentText) : null;
+ return {
+ type: 'session-link',
+ href: input.href,
+ label: input.label,
+ titled: input.titled,
+ ...(target?.messageClientId ? { messageClientId: target.messageClientId } : {}),
+ ...(bounded?.text ? { agentText: bounded.text } : {}),
+ ...((input.agentTextTruncated === true || bounded?.truncated === true)
+ ? { agentTextTruncated: true }
+ : {}),
+ };
+}
+
+/**
+ * Message chips can arrive from a pasted deep link before their readable body
+ * has finished loading from the source device. Resolve every missing body
+ * before serializing a send so an immediate tap cannot degrade the semantic
+ * reference to the deep link alone.
+ */
+export async function hydrateComposerMessageReferenceBodies(
+ document: ComposerDocument,
+ resolve: ResolveSessionLinkSemantic,
+): Promise<ComposerDocument> {
+ const hrefs = [...new Set(document.nodes.flatMap((node) => (
+ node.type === 'session-link' && node.messageClientId && !node.agentText
+ ? [node.href]
+ : []
+ )))];
+ if (hrefs.length === 0) return document;
+
+ const resolved = new Map<string, ResolvedSessionLinkSemantic>();
+ await Promise.all(hrefs.map(async (href) => {
+ try {
+ const semantic = await resolve(href);
+ if (semantic) resolved.set(href, semantic);
+ } catch {
+ // Keep the stable deep-link identity when the source device is unavailable.
+ }
+ }));
+ if (resolved.size === 0) return document;
+
+ return normalizeComposerDocument({
+ version: 1,
+ nodes: document.nodes.map((node) => {
+ if (node.type !== 'session-link' || node.agentText) return node;
+ const semantic = resolved.get(node.href);
+ if (!semantic) return node;
+ return sessionLinkComposerNode({
+ ...node,
+ label: semantic.label,
+ titled: true,
+ ...(semantic.agentText ? { agentText: semantic.agentText } : {}),
+ ...(semantic.agentTextTruncated ? { agentTextTruncated: true } : {}),
+ });
+ }),
+ });
+}
+
+export function pastedTextComposerNode(text: string): ComposerPastedTextNode {
+ const lineCount = text.length === 0 ? 0 : text.split('\n').length;
+ return {
+ type: 'pasted-text',
+ text,
+ display: `Pasted text (${lineCount} ${lineCount === 1 ? 'line' : 'lines'})`,
+ };
+}
+
+export function isLongComposerPaste(text: string): boolean {
+ if (text.length > MOBILE_LONG_PASTE_MAX_CHARS) return true;
+ if (text.length >= MOBILE_LONG_PASTE_CHAR_THRESHOLD) return true;
+ let lines = 1;
+ for (let index = 0; index < text.length; index += 1) {
+ if (text.charCodeAt(index) === 10 && ++lines >= MOBILE_LONG_PASTE_LINE_THRESHOLD) return true;
+ }
+ return false;
+}
+
+/** Restore a sent quotesEncoded body into its original quote/text order. */
+export function composerDocumentFromEncodedMessage(content: string): ComposerDocument {
+ return normalizeComposerDocument({
+ version: 1,
+ nodes: parseChatQuoteSegments(content).flatMap<ComposerNode>((segment) => (
+ segment.kind === 'quote'
+ ? [{ type: 'quote', quote: segment.quote }]
+ : segment.text ? [{ type: 'text', text: segment.text }] : []
+ )),
+ });
+}
+
+/** Restore all persisted composer presentation metadata into semantic nodes. */
+export function composerDocumentFromSerializedMessage(
+ content: string,
+ options: {
+ quotesEncoded?: boolean;
+ agentReferences?: readonly AgentInputReference[];
+ pastedTextRanges?: readonly ComposerPastedTextRange[];
+ slashCommandRanges?: readonly ComposerSlashCommandRange[];
+ } = {},
+): ComposerDocument {
+ const segments = options.quotesEncoded === true
+ ? parseChatQuoteSegments(content)
+ : [{ kind: 'text' as const, text: content }];
+ const starts = locateChatQuoteTextSegmentStarts(content, segments);
+ const nodes: ComposerNode[] = [];
+ segments.forEach((segment, index) => {
+ if (segment.kind === 'quote') {
+ nodes.push({ type: 'quote', quote: segment.quote });
+ return;
+ }
+ const sourceStart = starts[index];
+ const pastedTextRanges = projectSentRanges(
+ options.pastedTextRanges ?? [],
+ sourceStart,
+ segment.text.length,
+ );
+ const slashCommandRanges = projectSentRanges(
+ options.slashCommandRanges ?? [],
+ sourceStart,
+ segment.text.length,
+ );
+ const agentReferences = projectSentRanges(
+ options.agentReferences ?? [],
+ sourceStart,
+ segment.text.length,
+ );
+ nodes.push(...composerNodesFromTextSegment(
+ segment.text,
+ pastedTextRanges,
+ slashCommandRanges,
+ agentReferences,
+ ));
+ });
+ return normalizeComposerDocument({ version: 1, nodes });
+}
+
+/** One-way lift for the former `draft string + quote[]` persistence shape. */
+export function migrateLegacyComposerDraft(
+ text: string | null | undefined,
+ quotes: readonly ChatQuote[],
+ orderedBody?: string | null,
+): ComposerDocument {
+ if (orderedBody && quotes.length > 0) return composerDocumentFromEncodedMessage(orderedBody);
+ return normalizeComposerDocument({
+ version: 1,
+ nodes: [
+ ...quotes.map<ComposerQuoteNode>((quote) => ({ type: 'quote', quote })),
+ ...(text ? [{ type: 'text' as const, text }] : []),
+ ],
+ });
+}
+
+export function serializeComposerDocument(document: ComposerDocument): SerializedComposerDocument {
+ let serialized = '';
+ let previous: ComposerNode | null = null;
+ const pastedTextRanges: ComposerPastedTextRange[] = [];
+ const slashCommandRanges: ComposerSlashCommandRange[] = [];
+ const agentReferences: AgentInputReference[] = [];
+ let quotesEncoded = false;
+
+ for (const node of normalizeComposerDocument(document).nodes) {
+ const wire = composerNodeWireText(node);
+ if (!wire) continue;
+ const separator = previous && (previous.type === 'quote' || node.type === 'quote') ? '\n\n' : '';
+ serialized += separator;
+ const start = serialized.length;
+ serialized += wire;
+ if (node.type === 'session-link') {
+ const target = parseSessionDeepLinkUrl(node.href);
+ if (target?.messageClientId) {
+ agentReferences.push({
+ kind: 'message',
+ start,
+ end: start + wire.length,
+ href: node.href,
+ sessionId: target.sessionId,
+ messageClientId: target.messageClientId,
+ ...(node.agentText ? { text: node.agentText } : {}),
+ ...(node.agentTextTruncated ? { truncated: true } : {}),
+ });
+ } else if (target) {
+ agentReferences.push({
+ kind: 'session',
+ start,
+ end: start + wire.length,
+ href: node.href,
+ sessionId: target.sessionId,
+ ...(node.titled && node.label ? { title: node.label } : {}),
+ });
+ }
+ } else if (
+ node.type === 'mention'
+ && node.kind === 'project'
+ && node.href
+ && node.workingDir
+ ) {
+ agentReferences.push({
+ kind: 'project',
+ start,
+ end: start + wire.length,
+ href: node.href,
+ name: node.label,
+ workingDir: node.workingDir,
+ });
+ }
+ if (node.type === 'quote') quotesEncoded = true;
+ if (node.type === 'pasted-text') {
+ pastedTextRanges.push({ start, end: start + wire.length, display: node.display });
+ }
+ if (node.type === 'text' && node.slashCommand === node.text) {
+ slashCommandRanges.push({ start, end: start + wire.length });
+ }
+ previous = node;
+ }
+
+ const leadingTrim = serialized.length - serialized.trimStart().length;
+ const text = serialized.trim();
+ const trimRange = <T extends { start: number; end: number }>(range: T): T | null => {
+ const start = Math.max(0, range.start - leadingTrim);
+ const end = Math.min(text.length, range.end - leadingTrim);
+ return start < end ? { ...range, start, end } : null;
+ };
+ return {
+ text,
+ quotesEncoded,
+ agentReferences: agentReferences.map(trimRange).filter((reference): reference is AgentInputReference => !!reference),
+ pastedTextRanges: pastedTextRanges.map(trimRange).filter((range): range is ComposerPastedTextRange => !!range),
+ slashCommandRanges: slashCommandRanges.map(trimRange).filter((range): range is ComposerSlashCommandRange => !!range),
+ };
+}
+
+export function parseStoredComposerDocument(value: unknown): ComposerDocument | null {
+ if (!value || typeof value !== 'object') return null;
+ const candidate = value as { version?: unknown; nodes?: unknown };
+ if (candidate.version !== 1 || !Array.isArray(candidate.nodes)) return null;
+ return normalizeComposerDocument({ version: 1, nodes: candidate.nodes as ComposerNode[] });
+}
+
+function serializeSessionLink(node: ComposerSessionLinkNode): string {
+ if (node.messageClientId) return node.href;
+ const safeLabel = sanitizeComposerLinkLabel(node.label);
+ return node.titled && safeLabel ? `[${safeLabel}](${node.href})` : node.href;
+}
+
+export function sanitizeComposerLinkLabel(label: string): string {
+ return label.replace(/[[\]]/g, ' ').replace(/@/g, '@').replace(/\s+/g, ' ').trim();
+}
+
+function composerNodeFromSentToken(token: SentInlineToken): ComposerNode {
+ if (token.kind === 'quote') {
+ return { type: 'quote', quote: token.quote };
+ }
+ if (token.kind === 'pasted') {
+ return { type: 'pasted-text', text: token.text, display: token.display };
+ }
+ if (token.kind === 'slash') {
+ return { type: 'text', text: token.text, slashCommand: token.text };
+ }
+ return { type: 'text', text: token.text };
+}
+
+function compactReferenceLabel(value: string): string {
+ const compact = value.replace(/\s+/g, ' ').trim();
+ return compact.length <= 240 ? compact : `${compact.slice(0, 239)}…`;
+}
+
+function composerNodeFromAgentReference(
+ reference: AgentInputReference,
+ raw: string,
+): ComposerNode {
+ if (reference.kind === 'message') {
+ return sessionLinkComposerNode({
+ href: reference.href,
+ label: compactReferenceLabel(reference.text || reference.messageClientId),
+ titled: Boolean(reference.text),
+ ...(reference.text ? { agentText: reference.text } : {}),
+ ...(reference.truncated ? { agentTextTruncated: true } : {}),
+ });
+ }
+ if (reference.kind === 'session') {
+ return sessionLinkComposerNode({
+ href: reference.href,
+ label: reference.title || reference.sessionId,
+ titled: Boolean(reference.title),
+ });
+ }
+ return {
+ type: 'mention',
+ kind: 'project',
+ label: reference.name,
+ raw,
+ href: reference.href,
+ workingDir: reference.workingDir,
+ };
+}
+
+function composerNodesFromTextSegment(
+ text: string,
+ pastedTextRanges: readonly ComposerPastedTextRange[],
+ slashCommandRanges: readonly ComposerSlashCommandRange[],
+ agentReferences: readonly AgentInputReference[],
+): ComposerNode[] {
+ if (agentReferences.length === 0) {
+ return buildSentInlineTokens(text, pastedTextRanges, slashCommandRanges)
+ .map(composerNodeFromSentToken);
+ }
+ const nodes: ComposerNode[] = [];
+ let cursor = 0;
+ for (const reference of agentReferences) {
+ if (reference.start > cursor) {
+ const prefix = text.slice(cursor, reference.start);
+ nodes.push(...buildSentInlineTokens(
+ prefix,
+ projectSentRanges(pastedTextRanges, cursor, prefix.length),
+ projectSentRanges(slashCommandRanges, cursor, prefix.length),
+ ).map(composerNodeFromSentToken));
+ }
+ nodes.push(composerNodeFromAgentReference(
+ reference,
+ text.slice(reference.start, reference.end),
+ ));
+ cursor = reference.end;
+ }
+ if (cursor < text.length) {
+ const suffix = text.slice(cursor);
+ nodes.push(...buildSentInlineTokens(
+ suffix,
+ projectSentRanges(pastedTextRanges, cursor, suffix.length),
+ projectSentRanges(slashCommandRanges, cursor, suffix.length),
+ ).map(composerNodeFromSentToken));
+ }
+ return nodes;
+}
+
+function composerNodeWireText(node: ComposerNode): string {
+ switch (node.type) {
+ case 'text':
+ case 'pasted-text':
+ return node.text;
+ case 'quote':
+ return formatQuoteForSend(node.quote);
+ case 'mention':
+ return node.raw;
+ case 'session-link':
+ return serializeSessionLink(node);
+ }
+}
+
+function composerNodeProjectedText(node: ComposerNode): string {
+ if (node.type === 'quote') return '';
+ return composerNodeWireText(node);
+}
+
+function normalizeNode(node: ComposerNode): ComposerNode | null {
+ if (!node || typeof node !== 'object' || typeof node.type !== 'string') return null;
+ if (node.type === 'text') {
+ if (typeof node.text !== 'string' || node.text.length === 0) return null;
+ return {
+ type: 'text',
+ text: node.text,
+ ...(typeof node.slashCommand === 'string' && node.slashCommand === node.text
+ ? { slashCommand: node.slashCommand }
+ : {}),
+ };
+ }
+ if (node.type === 'quote') {
+ const quote = normalizeQuote(node.quote);
+ return quote ? { type: 'quote', quote } : null;
+ }
+ if (node.type === 'mention') {
+ if (
+ typeof node.kind !== 'string'
+ || !['file', 'dir', 'agent', 'project'].includes(node.kind)
+ || typeof node.raw !== 'string'
+ || !node.raw
+ || typeof node.label !== 'string'
+ || !node.label
+ ) return null;
+ if (node.kind === 'project') {
+ const legacyMarkdownHref = node.raw.startsWith('[') && node.raw.endsWith(')')
+ ? node.raw.slice(node.raw.lastIndexOf('](') + 2, -1)
+ : node.raw;
+ const href = typeof node.href === 'string' && node.href ? node.href : legacyMarkdownHref;
+ const parsed = parseProjectDeepLinkUrl(href);
+ if (!parsed) return null;
+ return {
+ type: 'mention',
+ kind: 'project',
+ raw: node.raw,
+ label: node.label,
+ href,
+ workingDir: parsed.workingDir,
+ };
+ }
+ return { type: 'mention', kind: node.kind, raw: node.raw, label: node.label };
+ }
+ if (node.type === 'session-link') {
+ if (
+ typeof node.href !== 'string'
+ || !node.href
+ || typeof node.label !== 'string'
+ || !node.label
+ || (node.titled !== undefined && typeof node.titled !== 'boolean')
+ || (node.messageClientId !== undefined && typeof node.messageClientId !== 'string')
+ || (node.agentText !== undefined && typeof node.agentText !== 'string')
+ || (
+ node.agentTextTruncated !== undefined
+ && typeof node.agentTextTruncated !== 'boolean'
+ )
+ || !parseSessionDeepLinkUrl(node.href)
+ ) return null;
+ return sessionLinkComposerNode(node);
+ }
+ if (node.type === 'pasted-text') {
+ if (
+ typeof node.text !== 'string'
+ || !node.text
+ || typeof node.display !== 'string'
+ || !node.display
+ ) return null;
+ return { type: 'pasted-text', text: node.text, display: node.display };
+ }
+ return null;
+}
+
+function normalizeQuote(value: unknown): ChatQuote | null {
+ if (!value || typeof value !== 'object') return null;
+ const quote = value as {
+ text?: unknown;
+ sourcePath?: unknown;
+ startLine?: unknown;
+ endLine?: unknown;
+ };
+ if (typeof quote.text !== 'string' || !quote.text) return null;
+ if (quote.sourcePath !== undefined && typeof quote.sourcePath !== 'string') return null;
+ if (quote.startLine !== undefined && !isPositiveLine(quote.startLine)) return null;
+ if (quote.endLine !== undefined && !isPositiveLine(quote.endLine)) return null;
+ if ((quote.startLine !== undefined || quote.endLine !== undefined) && !quote.sourcePath) return null;
+ if (quote.endLine !== undefined && quote.startLine === undefined) return null;
+ if (
+ typeof quote.startLine === 'number'
+ && typeof quote.endLine === 'number'
+ && quote.endLine < quote.startLine
+ ) return null;
+ return {
+ text: quote.text,
+ ...(quote.sourcePath !== undefined ? { sourcePath: quote.sourcePath } : {}),
+ ...(typeof quote.startLine === 'number' ? { startLine: quote.startLine } : {}),
+ ...(typeof quote.endLine === 'number' ? { endLine: quote.endLine } : {}),
+ };
+}
+
+function isPositiveLine(value: unknown): value is number {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
+}
diff --git a/apps/mobile/src/session/composerDraftStore.ts b/apps/mobile/src/session/composerDraftStore.ts
index 28977c50ea..5a383bc238 100644
--- a/apps/mobile/src/session/composerDraftStore.ts
+++ b/apps/mobile/src/session/composerDraftStore.ts
@@ -1,11 +1,16 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
+import { parseStoredComposerDocument, type ComposerDocument } from '@/session/composerDocument';
const STORAGE_KEY_PREFIX = 'xdt.mobileComposerDraft.v1';
+const DOCUMENT_STORAGE_KEY_PREFIX = 'xdt.mobileComposerDocument.v1';
const PERSIST_DEBOUNCE_MS = 400;
const drafts = new Map<string, string>();
const clearedDrafts = new Set<string>();
+const clearedDocumentDrafts = new Set<string>();
const pendingPersistTimers = new Map<string, ReturnType<typeof setTimeout>>();
+const pendingDocumentPersistTimers = new Map<string, ReturnType<typeof setTimeout>>();
const pendingStorageOperations = new Map<string, Promise<void>>();
+const documentDrafts = new Map<string, ComposerDocument>();
export function saveComposerDraft(sessionId: string, text: string | null | undefined): void {
const normalizedSessionId = normalizeSessionId(sessionId);
@@ -26,6 +31,50 @@ export function saveComposerDraft(sessionId: string, text: string | null | undef
schedulePersist(normalizedSessionId, key, value);
}
+export function saveComposerDocumentDraft(sessionId: string, document: ComposerDocument): void {
+ const normalizedSessionId = normalizeSessionId(sessionId);
+ if (!normalizedSessionId) return;
+ const key = documentStorageKeyForSession(normalizedSessionId);
+ if (document.nodes.length === 0) {
+ cancelPendingDocumentPersist(normalizedSessionId);
+ documentDrafts.delete(normalizedSessionId);
+ clearedDocumentDrafts.add(normalizedSessionId);
+ enqueueStorageOperation(normalizedSessionId, () => AsyncStorage.removeItem(key));
+ return;
+ }
+ documentDrafts.set(normalizedSessionId, document);
+ clearedDocumentDrafts.delete(normalizedSessionId);
+ const serialized = JSON.stringify(document);
+ scheduleDocumentPersist(normalizedSessionId, key, document, serialized);
+}
+
+export function readComposerDocumentDraftSync(sessionId: string): ComposerDocument | null {
+ const normalizedSessionId = normalizeSessionId(sessionId);
+ if (!normalizedSessionId || clearedDocumentDrafts.has(normalizedSessionId)) return null;
+ return documentDrafts.get(normalizedSessionId) ?? null;
+}
+
+export async function readComposerDocumentDraft(sessionId: string): Promise<ComposerDocument | null> {
+ const normalizedSessionId = normalizeSessionId(sessionId);
+ if (!normalizedSessionId) return null;
+ const memory = documentDrafts.get(normalizedSessionId);
+ if (memory) return memory;
+ if (clearedDocumentDrafts.has(normalizedSessionId)) return null;
+ const stored = await AsyncStorage.getItem(documentStorageKeyForSession(normalizedSessionId)).catch(() => null);
+ const freshMemory = documentDrafts.get(normalizedSessionId);
+ if (freshMemory) return freshMemory;
+ if (clearedDocumentDrafts.has(normalizedSessionId)) return null;
+ if (!stored) return null;
+ try {
+ const parsed = parseStoredComposerDocument(JSON.parse(stored));
+ if (!parsed) return null;
+ documentDrafts.set(normalizedSessionId, parsed);
+ return parsed;
+ } catch {
+ return null;
+ }
+}
+
export function readComposerDraftSync(sessionId: string): string | null {
const normalizedSessionId = normalizeSessionId(sessionId);
if (!normalizedSessionId) return null;
@@ -60,18 +109,29 @@ export function clearComposerDraft(sessionId: string): void {
const normalizedSessionId = normalizeSessionId(sessionId);
if (!normalizedSessionId) return;
cancelPendingPersist(normalizedSessionId);
+ cancelPendingDocumentPersist(normalizedSessionId);
drafts.delete(normalizedSessionId);
clearedDrafts.add(normalizedSessionId);
- enqueueStorageOperation(normalizedSessionId, () => AsyncStorage.removeItem(storageKeyForSession(normalizedSessionId)));
+ documentDrafts.delete(normalizedSessionId);
+ clearedDocumentDrafts.add(normalizedSessionId);
+ enqueueStorageOperation(normalizedSessionId, () => AsyncStorage.multiRemove([
+ storageKeyForSession(normalizedSessionId),
+ documentStorageKeyForSession(normalizedSessionId),
+ ]));
}
export async function clearComposerDrafts(): Promise<void> {
cancelAllPendingPersists();
+ cancelAllPendingDocumentPersists();
drafts.clear();
+ documentDrafts.clear();
clearedDrafts.clear();
+ clearedDocumentDrafts.clear();
await drainPendingStorageOperations();
const keys = await AsyncStorage.getAllKeys().catch(() => [] as readonly string[]);
- const ownedKeys = keys.filter((key) => key.startsWith(`${STORAGE_KEY_PREFIX}.`));
+ const ownedKeys = keys.filter((key) => (
+ key.startsWith(`${STORAGE_KEY_PREFIX}.`) || key.startsWith(`${DOCUMENT_STORAGE_KEY_PREFIX}.`)
+ ));
if (ownedKeys.length === 0) return;
await AsyncStorage.multiRemove(ownedKeys).catch(() => undefined);
}
@@ -84,17 +144,38 @@ export async function flushComposerDraftWrites(sessionId?: string): Promise<void
? [[normalizedSessionId, pendingPersistTimers.get(normalizedSessionId)!] as const]
: []
: [...pendingPersistTimers.entries()];
+ const pendingDocuments = normalizedSessionId
+ ? pendingDocumentPersistTimers.has(normalizedSessionId)
+ ? [[normalizedSessionId, pendingDocumentPersistTimers.get(normalizedSessionId)!] as const]
+ : []
+ : [...pendingDocumentPersistTimers.entries()];
for (const [pendingSessionId, timer] of pending) {
clearTimeout(timer);
pendingPersistTimers.delete(pendingSessionId);
}
+ for (const [pendingSessionId, timer] of pendingDocuments) {
+ clearTimeout(timer);
+ pendingDocumentPersistTimers.delete(pendingSessionId);
+ }
- await Promise.all(pending.map(([pendingSessionId]) => {
- const value = drafts.get(pendingSessionId);
- if (value === undefined) return Promise.resolve();
- return persistIfCurrent(pendingSessionId, storageKeyForSession(pendingSessionId), value);
- }));
+ await Promise.all([
+ ...pending.map(([pendingSessionId]) => {
+ const value = drafts.get(pendingSessionId);
+ if (value === undefined) return Promise.resolve();
+ return persistIfCurrent(pendingSessionId, storageKeyForSession(pendingSessionId), value);
+ }),
+ ...pendingDocuments.map(([pendingSessionId]) => {
+ const document = documentDrafts.get(pendingSessionId);
+ if (!document) return Promise.resolve();
+ return persistDocumentIfCurrent(
+ pendingSessionId,
+ documentStorageKeyForSession(pendingSessionId),
+ document,
+ JSON.stringify(document),
+ );
+ }),
+ ]);
await drainPendingStorageOperations(normalizedSessionId);
}
@@ -106,6 +187,10 @@ function storageKeyForSession(normalizedSessionId: string): string {
return `${STORAGE_KEY_PREFIX}.${encodeURIComponent(normalizedSessionId)}`;
}
+function documentStorageKeyForSession(normalizedSessionId: string): string {
+ return `${DOCUMENT_STORAGE_KEY_PREFIX}.${encodeURIComponent(normalizedSessionId)}`;
+}
+
function schedulePersist(normalizedSessionId: string, key: string, value: string): void {
cancelPendingPersist(normalizedSessionId);
const timer = setTimeout(() => {
@@ -115,6 +200,20 @@ function schedulePersist(normalizedSessionId: string, key: string, value: string
pendingPersistTimers.set(normalizedSessionId, timer);
}
+function scheduleDocumentPersist(
+ normalizedSessionId: string,
+ key: string,
+ document: ComposerDocument,
+ serialized: string,
+): void {
+ cancelPendingDocumentPersist(normalizedSessionId);
+ const timer = setTimeout(() => {
+ pendingDocumentPersistTimers.delete(normalizedSessionId);
+ void persistDocumentIfCurrent(normalizedSessionId, key, document, serialized);
+ }, PERSIST_DEBOUNCE_MS);
+ pendingDocumentPersistTimers.set(normalizedSessionId, timer);
+}
+
function cancelPendingPersist(normalizedSessionId: string): void {
const timer = pendingPersistTimers.get(normalizedSessionId);
if (!timer) return;
@@ -122,17 +221,40 @@ function cancelPendingPersist(normalizedSessionId: string): void {
pendingPersistTimers.delete(normalizedSessionId);
}
+function cancelPendingDocumentPersist(normalizedSessionId: string): void {
+ const timer = pendingDocumentPersistTimers.get(normalizedSessionId);
+ if (!timer) return;
+ clearTimeout(timer);
+ pendingDocumentPersistTimers.delete(normalizedSessionId);
+}
+
function cancelAllPendingPersists(): void {
for (const timer of pendingPersistTimers.values()) clearTimeout(timer);
pendingPersistTimers.clear();
}
+function cancelAllPendingDocumentPersists(): void {
+ for (const timer of pendingDocumentPersistTimers.values()) clearTimeout(timer);
+ pendingDocumentPersistTimers.clear();
+}
+
async function persistIfCurrent(normalizedSessionId: string, key: string, value: string): Promise<void> {
if (clearedDrafts.has(normalizedSessionId)) return;
if (drafts.get(normalizedSessionId) !== value) return;
await enqueueStorageOperation(normalizedSessionId, () => AsyncStorage.setItem(key, value));
}
+async function persistDocumentIfCurrent(
+ normalizedSessionId: string,
+ key: string,
+ document: ComposerDocument,
+ serialized: string,
+): Promise<void> {
+ if (clearedDocumentDrafts.has(normalizedSessionId)) return;
+ if (documentDrafts.get(normalizedSessionId) !== document) return;
+ await enqueueStorageOperation(normalizedSessionId, () => AsyncStorage.setItem(key, serialized));
+}
+
function enqueueStorageOperation(
normalizedSessionId: string,
operation: () => Promise<void>,
@@ -161,6 +283,7 @@ async function drainPendingStorageOperations(normalizedSessionId?: string): Prom
}
export const __testing = {
+ documentStorageKeyForSession,
persistDebounceMs: PERSIST_DEBOUNCE_MS,
storageKeyForSession,
storageKeyPrefix: STORAGE_KEY_PREFIX,
diff --git a/apps/mobile/src/session/composerPaste.ts b/apps/mobile/src/session/composerPaste.ts
new file mode 100644
index 0000000000..666a4014b6
--- /dev/null
+++ b/apps/mobile/src/session/composerPaste.ts
@@ -0,0 +1,157 @@
+import {
+ isLongComposerPaste,
+ normalizeComposerDocument,
+ pastedTextComposerNode,
+ sanitizeComposerLinkLabel,
+ sessionLinkComposerNode,
+ type ComposerNode,
+} from '@/session/composerDocument';
+import {
+ findMarkdownLabelStart,
+ parseProjectDeepLinkUrl,
+ parseSessionDeepLinkUrl,
+ projectDisplayName,
+ PROJECT_DEEP_LINK_RE_SOURCE,
+ SESSION_DEEP_LINK_RE_SOURCE,
+ shortSessionId,
+ unescapeMarkdownLabelBrackets,
+} from '@/session/sessionLinks';
+import { MAX_PASTED_TEXT_CHARS } from '@/session/composerRichInputProtocol';
+
+interface PasteCandidate {
+ end: number;
+ href: string;
+ kind: 'project' | 'session';
+ label: string | null;
+ start: number;
+}
+
+const TRAILING_PUNCTUATION = /[.,;:!?]+$/;
+
+/**
+ * Convert one user-initiated plain-text paste into semantic composer nodes.
+ * Long text wins over deep-link recognition so logs containing links stay one
+ * compact pasted-text atom, matching the desktop composer.
+ */
+export function composerNodesForPlainTextPaste(text: string): ComposerNode[] {
+ if (!text) return [];
+ if (isLongComposerPaste(text)) return [pastedTextComposerNode(text)];
+
+ const candidates = findDeepLinkCandidates(text);
+ if (candidates.length === 0) return [{ type: 'text', text }];
+
+ const nodes: ComposerNode[] = [];
+ let cursor = 0;
+ for (const candidate of candidates) {
+ if (candidate.start < cursor) continue;
+ if (candidate.start > cursor) {
+ nodes.push({ type: 'text', text: text.slice(cursor, candidate.start) });
+ }
+ const node = candidate.kind === 'session'
+ ? sessionNodeForCandidate(candidate)
+ : projectNodeForCandidate(candidate);
+ if (node) nodes.push(node);
+ else nodes.push({ type: 'text', text: text.slice(candidate.start, candidate.end) });
+ cursor = candidate.end;
+ }
+ if (cursor < text.length) nodes.push({ type: 'text', text: text.slice(cursor) });
+ return normalizeComposerDocument({ version: 1, nodes }).nodes;
+}
+
+/** Apply the native clipboard fallback limit before constructing Composer nodes. */
+export function composerNodesForBoundedPlainTextPaste(text: string): ComposerNode[] | null {
+ if (text.length > MAX_PASTED_TEXT_CHARS) return null;
+ return composerNodesForPlainTextPaste(text);
+}
+
+function findDeepLinkCandidates(text: string): PasteCandidate[] {
+ const candidates: PasteCandidate[] = [];
+ const markdownClose = new RegExp(
+ `\\]\\((?:(${SESSION_DEEP_LINK_RE_SOURCE})|(${PROJECT_DEEP_LINK_RE_SOURCE}))\\)`,
+ 'g',
+ );
+ let match: RegExpExecArray | null;
+ while ((match = markdownClose.exec(text)) !== null) {
+ const href = match[1] ?? match[2];
+ const kind = match[1] !== undefined ? 'session' : 'project';
+ if (!isValidTarget(kind, href)) continue;
+ const labelStart = findMarkdownLabelStart(text, match.index);
+ if (labelStart < 0) continue;
+ const rawLabel = unescapeMarkdownLabelBrackets(
+ text.slice(labelStart + 1, match.index),
+ ).trim();
+ candidates.push({
+ end: match.index + match[0].length,
+ href,
+ kind,
+ label: rawLabel && rawLabel !== href ? rawLabel : null,
+ start: labelStart,
+ });
+ }
+
+ const bare = new RegExp(
+ `(${SESSION_DEEP_LINK_RE_SOURCE})|(${PROJECT_DEEP_LINK_RE_SOURCE})`,
+ 'g',
+ );
+ while ((match = bare.exec(text)) !== null) {
+ const kind = match[1] !== undefined ? 'session' : 'project';
+ const href = match[0].replace(TRAILING_PUNCTUATION, '');
+ if (!isValidTarget(kind, href)) continue;
+ candidates.push({
+ end: match.index + href.length,
+ href,
+ kind,
+ label: null,
+ start: match.index,
+ });
+ }
+
+ candidates.sort((a, b) => a.start - b.start || b.end - a.end);
+ return candidates;
+}
+
+function isValidTarget(kind: PasteCandidate['kind'], href: string): boolean {
+ return kind === 'session'
+ ? parseSessionDeepLinkUrl(href) !== null
+ : parseProjectDeepLinkUrl(href) !== null;
+}
+
+function sessionNodeForCandidate(candidate: PasteCandidate): ComposerNode | null {
+ const target = parseSessionDeepLinkUrl(candidate.href);
+ if (!target) return null;
+ const explicitLabel = candidate.label
+ ? sanitizeComposerLinkLabel(candidate.label)
+ : '';
+ if (target.messageClientId) {
+ return sessionLinkComposerNode({
+ href: candidate.href,
+ label: shortSessionId(target.messageClientId),
+ titled: false,
+ });
+ }
+ return sessionLinkComposerNode({
+ href: candidate.href,
+ label: explicitLabel || shortSessionId(target.sessionId),
+ titled: explicitLabel.length > 0,
+ });
+}
+
+function projectNodeForCandidate(candidate: PasteCandidate): ComposerNode | null {
+ const target = parseProjectDeepLinkUrl(candidate.href);
+ if (!target) return null;
+ const explicitLabel = candidate.label
+ ? sanitizeComposerLinkLabel(candidate.label)
+ : '';
+ const label = explicitLabel || projectDisplayName(target.workingDir);
+ const raw = explicitLabel
+ ? `[${explicitLabel}](${candidate.href})`
+ : candidate.href;
+ return {
+ type: 'mention',
+ kind: 'project',
+ label,
+ raw,
+ href: candidate.href,
+ workingDir: target.workingDir,
+ };
+}
diff --git a/apps/mobile/src/session/composerRichInputHtml.ts b/apps/mobile/src/session/composerRichInputHtml.ts
new file mode 100644
index 0000000000..2688f3ff98
--- /dev/null
+++ b/apps/mobile/src/session/composerRichInputHtml.ts
@@ -0,0 +1,467 @@
+/** Self-contained HTML runtime for the mobile inline-atom composer WebView. */
+import type { ComposerDocument } from '@/session/composerDocument';
+import {
+ MAX_PASTED_IMAGE_BASE64_CHARS,
+ MAX_PASTED_IMAGE_COUNT,
+ MAX_PASTED_IMAGE_NAME_CHARS,
+ SUPPORTED_PASTED_IMAGE_MIME_TYPES,
+} from '@/session/composerRichInputProtocol';
+
+export interface ComposerRichInputTheme {
+ background: string;
+ border: string;
+ chip: string;
+ focus: string;
+ placeholder: string;
+ text: string;
+ textSecondary: string;
+}
+
+export interface ComposerRichInputConfig {
+ accessibilityLabel: string;
+ document: ComposerDocument;
+ editable: boolean;
+ maxHeight: number;
+ placeholder: string;
+ theme: ComposerRichInputTheme;
+}
+
+/**
+ * The editor intentionally has no network dependencies. Native owns the
+ * semantic document; this page owns IME/selection and reports normalized DOM
+ * changes after composition commits.
+ */
+export function buildComposerRichInputHtml(config: ComposerRichInputConfig): string {
+ const bootstrap = JSON.stringify(config).replace(/</g, '\\u003c');
+ return `<!doctype html>
+<html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
+<style>
+ :root { color-scheme: light dark; }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; background: transparent; overflow: hidden; }
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
+ #editor {
+ color: var(--text); caret-color: var(--focus); font-size: 15px; line-height: 22px;
+ min-height: 28px; max-height: var(--max-height); overflow-y: auto; outline: none;
+ padding: 3px 0; white-space: pre-wrap; overflow-wrap: anywhere; -webkit-user-select: text;
+ }
+ #editor:empty::before { content: attr(data-placeholder); color: var(--placeholder); pointer-events: none; }
+ .atom {
+ display: inline-flex; align-items: center; max-width: min(240px, 72vw);
+ position: relative; top: -1px; margin: 0 2px; padding: 2px 8px;
+ vertical-align: middle; border: 1px solid var(--border);
+ border-radius: 9999px; background: var(--chip); color: var(--text); font-size: 12px;
+ line-height: 20px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+ -webkit-touch-callout: none; -webkit-user-select: none; user-select: none;
+ }
+ .atom::before { content: attr(data-icon); margin-right: 6px; color: var(--secondary); }
+ .slash {
+ color: var(--text); background: var(--chip); border: 1px solid var(--border);
+ border-radius: 9999px; margin: 0 2px; padding: 2px 8px; font: inherit;
+ box-decoration-break: clone; -webkit-box-decoration-break: clone;
+ }
+ @media (prefers-reduced-motion: reduce) { * { scroll-behavior: auto !important; } }
+</style></head><body>
+<div id="editor" role="textbox" aria-multiline="true" spellcheck="true"></div>
+<script>
+(() => {
+ let config = ${bootstrap};
+ const root = document.getElementById('editor');
+ const style = document.documentElement.style;
+ const applyConfig = (next) => {
+ config = Object.assign({}, config, next, { theme: Object.assign({}, config.theme, next.theme || {}) });
+ style.setProperty('--text', config.theme.text);
+ style.setProperty('--secondary', config.theme.textSecondary);
+ style.setProperty('--placeholder', config.theme.placeholder);
+ style.setProperty('--chip', config.theme.chip);
+ style.setProperty('--border', config.theme.border);
+ style.setProperty('--focus', config.theme.focus);
+ style.setProperty('--max-height', config.maxHeight + 'px');
+ root.dataset.placeholder = config.placeholder;
+ root.setAttribute('aria-label', config.accessibilityLabel);
+ root.contentEditable = config.editable ? 'true' : 'false';
+ };
+ applyConfig(config);
+
+ let applying = false;
+ let composing = false;
+ let lastSignature = '';
+ let pasteRequestSequence = 0;
+ const pasteMarkers = new Map();
+ const CARET_ANCHOR = '\\u200B';
+ const MAX_PASTED_IMAGE_BASE64_CHARS = ${MAX_PASTED_IMAGE_BASE64_CHARS};
+ const MAX_PASTED_IMAGE_COUNT = ${MAX_PASTED_IMAGE_COUNT};
+ const MAX_PASTED_IMAGE_NAME_CHARS = ${MAX_PASTED_IMAGE_NAME_CHARS};
+ const SUPPORTED_PASTED_IMAGE_MIME_TYPES = new Set(${JSON.stringify(SUPPORTED_PASTED_IMAGE_MIME_TYPES)});
+
+ const post = (payload) => {
+ if (window.ReactNativeWebView) window.ReactNativeWebView.postMessage(JSON.stringify(payload));
+ };
+ const isCaretAnchor = (node) =>
+ Boolean(node && node.nodeType === Node.TEXT_NODE && String(node.nodeValue || '').startsWith(CARET_ANCHOR));
+ const isEmptyCaretAnchor = (node) => isCaretAnchor(node) && node.nodeValue === CARET_ANCHOR;
+ const makeCaretAnchor = () => document.createTextNode(CARET_ANCHOR);
+ const atomLabel = (node) => {
+ if (node.type === 'quote') return String(node.quote && node.quote.text || '').replace(/\\s+/g, ' ').trim();
+ if (node.type === 'mention' || node.type === 'session-link') return node.label;
+ if (node.type === 'pasted-text') return node.display;
+ return '';
+ };
+ const atomIcon = (node) => {
+ if (node.type === 'quote' || (node.type === 'session-link' && node.messageClientId)) return '❝';
+ if (node.type === 'mention') return node.kind === 'dir' || node.kind === 'project' ? '⌁' : node.kind === 'agent' ? '◇' : '▧';
+ if (node.type === 'session-link') return '↳';
+ return '▤';
+ };
+ const makeNode = (node) => {
+ if (node.type === 'text') {
+ if (node.slashCommand === node.text) {
+ const mark = document.createElement('span');
+ mark.className = 'slash';
+ mark.dataset.slashValue = node.slashCommand;
+ mark.textContent = node.text;
+ return mark;
+ }
+ return document.createTextNode(node.text);
+ }
+ const atom = document.createElement('span');
+ atom.className = 'atom';
+ atom.contentEditable = 'false';
+ atom.dataset.node = encodeURIComponent(JSON.stringify(node));
+ atom.dataset.icon = atomIcon(node);
+ atom.textContent = atomLabel(node) || 'Reference';
+ atom.setAttribute('role', 'button');
+ atom.setAttribute('aria-label', atomLabel(node) || 'Reference');
+ atom.tabIndex = -1;
+ return atom;
+ };
+ const makeDomNodes = (node) => {
+ const element = makeNode(node);
+ return node.type === 'text' ? [element] : [element, makeCaretAnchor()];
+ };
+ const render = (documentValue, focusAfter) => {
+ applying = true;
+ root.replaceChildren(...(documentValue.nodes || []).flatMap(makeDomNodes));
+ applying = false;
+ lastSignature = JSON.stringify(readDocument());
+ reportHeight();
+ if (focusAfter) placeCaretAtEnd();
+ };
+ const pushText = (nodes, text, slashCommand) => {
+ if (!text) return;
+ const previous = nodes[nodes.length - 1];
+ if (previous && previous.type === 'text' && previous.slashCommand === slashCommand) previous.text += text;
+ else nodes.push(Object.assign({ type: 'text', text }, slashCommand ? { slashCommand } : {}));
+ };
+ const walk = (parent, nodes) => {
+ const children = Array.from(parent.childNodes);
+ children.forEach((child, index) => {
+ if (child.nodeType === Node.TEXT_NODE) {
+ pushText(nodes, String(child.nodeValue || '').split(CARET_ANCHOR).join(''));
+ return;
+ }
+ if (child.nodeType !== Node.ELEMENT_NODE) return;
+ const element = child;
+ if (element.classList.contains('atom') && element.dataset.node) {
+ try { nodes.push(JSON.parse(decodeURIComponent(element.dataset.node))); } catch (_) {}
+ return;
+ }
+ if (element.tagName === 'BR') {
+ pushText(nodes, '\\n');
+ return;
+ }
+ if (element.classList.contains('slash')) {
+ const value = element.textContent || '';
+ const mark = value === element.dataset.slashValue ? value : undefined;
+ pushText(nodes, value, mark);
+ return;
+ }
+ const before = nodes.length ? nodes[nodes.length - 1] : null;
+ walk(element, nodes);
+ const isBlock = /^(DIV|P|LI)$/.test(element.tagName);
+ if (isBlock && index < children.length - 1) {
+ const after = nodes.length ? nodes[nodes.length - 1] : null;
+ if (after !== before || (after && after.type === 'text')) pushText(nodes, '\\n');
+ }
+ });
+ };
+ const readDocument = () => {
+ const nodes = [];
+ walk(root, nodes);
+ return { version: 1, nodes };
+ };
+ const reportHeight = () => post({ type: 'height', height: Math.min(config.maxHeight, Math.max(28, root.scrollHeight)) });
+ const notify = () => {
+ if (applying || composing) return;
+ const value = readDocument();
+ const signature = JSON.stringify(value);
+ if (signature !== lastSignature) {
+ lastSignature = signature;
+ post({ type: 'change', document: value });
+ }
+ reportHeight();
+ };
+ const setCaretAfter = (node, selection) => {
+ const range = document.createRange();
+ if (isCaretAnchor(node)) {
+ range.setStart(node, Math.min(CARET_ANCHOR.length, String(node.nodeValue || '').length));
+ } else if (node && node.nodeType === Node.TEXT_NODE) {
+ range.setStart(node, String(node.nodeValue || '').length);
+ } else {
+ range.setStartAfter(node);
+ }
+ range.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(range);
+ };
+ const placeCaretAtEnd = () => {
+ root.focus();
+ const selection = window.getSelection();
+ if (!selection) return;
+ const last = root.lastChild;
+ if (last) {
+ setCaretAfter(last, selection);
+ return;
+ }
+ const range = document.createRange();
+ range.selectNodeContents(root);
+ range.collapse(false);
+ selection.removeAllRanges();
+ selection.addRange(range);
+ };
+ const insertAtSelection = (node) => {
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0 || !root.contains(selection.anchorNode)) placeCaretAtEnd();
+ const current = window.getSelection();
+ if (!current || current.rangeCount === 0) return;
+ const range = current.getRangeAt(0);
+ range.deleteContents();
+ const inserted = makeDomNodes(node);
+ const fragment = document.createDocumentFragment();
+ inserted.forEach((element) => fragment.appendChild(element));
+ range.insertNode(fragment);
+ setCaretAfter(inserted[inserted.length - 1], current);
+ notify();
+ };
+ const createPasteMarker = () => {
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0 || !root.contains(selection.anchorNode)) placeCaretAtEnd();
+ const current = window.getSelection();
+ if (!current || current.rangeCount === 0) return null;
+ const range = current.getRangeAt(0);
+ range.deleteContents();
+ const requestId = String(++pasteRequestSequence);
+ const marker = document.createComment('cindy-paste:' + requestId);
+ range.insertNode(marker);
+ const anchor = makeCaretAnchor();
+ marker.parentNode.insertBefore(anchor, marker.nextSibling);
+ setCaretAfter(anchor, current);
+ pasteMarkers.set(requestId, { marker, anchor });
+ return requestId;
+ };
+ const commitPaste = (requestId, nodes) => {
+ const pending = pasteMarkers.get(requestId);
+ pasteMarkers.delete(requestId);
+ const marker = pending && pending.marker;
+ if (!marker || !marker.parentNode) return;
+ const inserted = (Array.isArray(nodes) ? nodes : []).flatMap(makeDomNodes);
+ inserted.forEach((node) => marker.parentNode.insertBefore(node, marker));
+ const selection = window.getSelection();
+ const trailing = pending && pending.anchor;
+ if (trailing && trailing.parentNode) trailing.remove();
+ marker.remove();
+ if (selection && inserted.length > 0) setCaretAfter(inserted[inserted.length - 1], selection);
+ root.focus();
+ notify();
+ };
+ const resolveSessionLink = (href, semantic) => {
+ const label = semantic && semantic.label;
+ if (!href || !label) return;
+ let changed = false;
+ root.querySelectorAll('.atom').forEach((atom) => {
+ if (!atom.dataset.node) return;
+ try {
+ const node = JSON.parse(decodeURIComponent(atom.dataset.node));
+ if (node.type !== 'session-link' || node.href !== href || node.titled) return;
+ const next = Object.assign({}, node, semantic, { label, titled: true });
+ atom.dataset.node = encodeURIComponent(JSON.stringify(next));
+ atom.textContent = label;
+ atom.setAttribute('aria-label', label);
+ changed = true;
+ } catch (_) {}
+ });
+ if (changed) notify();
+ };
+ const asAtom = (node) =>
+ node && node.nodeType === Node.ELEMENT_NODE && node.classList.contains('atom') ? node : null;
+ const atomAcrossEmptyAnchor = (node, backward) => {
+ let candidate = node;
+ if (isEmptyCaretAnchor(candidate)) {
+ candidate = backward ? candidate.previousSibling : candidate.nextSibling;
+ }
+ return asAtom(candidate);
+ };
+ const adjacentAtom = (backward) => {
+ const selection = window.getSelection();
+ if (!selection || !selection.isCollapsed || selection.rangeCount === 0) return null;
+ const range = selection.getRangeAt(0);
+ let container = range.startContainer;
+ let offset = range.startOffset;
+ if (container === root || container.nodeType === Node.ELEMENT_NODE) {
+ const child = container.childNodes[backward ? offset - 1 : offset];
+ return atomAcrossEmptyAnchor(child, backward);
+ }
+ if (isCaretAnchor(container)) {
+ if (backward && offset <= CARET_ANCHOR.length) return asAtom(container.previousSibling);
+ if (!backward && offset >= String(container.nodeValue || '').length) return asAtom(container.nextSibling);
+ return null;
+ }
+ if (container.nodeType === Node.TEXT_NODE && ((backward && offset === 0) || (!backward && offset === container.nodeValue.length))) {
+ const sibling = backward ? container.previousSibling : container.nextSibling;
+ return atomAcrossEmptyAnchor(sibling, backward);
+ }
+ return null;
+ };
+ const removeAtom = (atom) => {
+ const parent = atom.parentNode;
+ if (!parent) return;
+ const index = Array.prototype.indexOf.call(parent.childNodes, atom);
+ const anchor = atom.nextSibling;
+ let trailing = null;
+ if (isCaretAnchor(anchor)) {
+ const text = String(anchor.nodeValue || '').slice(CARET_ANCHOR.length);
+ if (text) {
+ anchor.nodeValue = text;
+ trailing = anchor;
+ } else {
+ anchor.remove();
+ }
+ }
+ atom.remove();
+ const selection = window.getSelection();
+ if (selection) {
+ const range = document.createRange();
+ if (trailing) range.setStart(trailing, 0);
+ else range.setStart(parent, Math.min(index, parent.childNodes.length));
+ range.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(range);
+ }
+ };
+ const isolateCaretAnchor = (atom) => {
+ let anchor = atom.nextSibling;
+ if (!isCaretAnchor(anchor)) {
+ anchor = makeCaretAnchor();
+ atom.parentNode.insertBefore(anchor, atom.nextSibling);
+ return anchor;
+ }
+ const trailing = String(anchor.nodeValue || '').slice(CARET_ANCHOR.length);
+ if (trailing) {
+ anchor.nodeValue = CARET_ANCHOR;
+ anchor.parentNode.insertBefore(document.createTextNode(trailing), anchor.nextSibling);
+ }
+ return anchor;
+ };
+ const elementDropRange = (element, clientX, pairAnchor) => {
+ const range = document.createRange();
+ const rect = element.getBoundingClientRect();
+ if (clientX < rect.left + rect.width / 2) range.setStartBefore(element);
+ else range.setStartAfter(pairAnchor || element);
+ range.collapse(true);
+ return range;
+ };
+ const placeCaretAroundAtom = (atom, clientX) => {
+ root.focus();
+ const selection = window.getSelection();
+ if (!selection) return;
+ const range = elementDropRange(atom, clientX, isolateCaretAnchor(atom));
+ selection.removeAllRanges();
+ selection.addRange(range);
+ };
+
+ root.addEventListener('input', notify);
+ root.addEventListener('compositionstart', () => { composing = true; });
+ root.addEventListener('compositionend', () => { composing = false; notify(); });
+ root.addEventListener('focus', () => post({ type: 'focus' }));
+ root.addEventListener('blur', () => post({ type: 'blur' }));
+ root.addEventListener('keydown', (event) => {
+ const backward = event.key === 'Backspace';
+ if (!backward && event.key !== 'Delete') return;
+ const atom = adjacentAtom(backward);
+ if (!atom) return;
+ event.preventDefault();
+ removeAtom(atom);
+ notify();
+ });
+ root.addEventListener('paste', (event) => {
+ const items = Array.from(event.clipboardData && event.clipboardData.items || []);
+ const images = items
+ .filter((item) => item.type && item.type.startsWith('image/'))
+ .slice(0, MAX_PASTED_IMAGE_COUNT);
+ if (images.length) {
+ event.preventDefault();
+ const requestId = 'images-' + String(++pasteRequestSequence);
+ post({ type: 'paste-images-start', requestId, count: images.length });
+ images.forEach((item, index) => {
+ const file = item.getAsFile();
+ if (!file) return post({ type: 'paste-image-failed', requestId, index });
+ const mimeType = file.type || item.type;
+ const name = file.name || ('pasted-image-' + index);
+ if (!SUPPORTED_PASTED_IMAGE_MIME_TYPES.has(mimeType) || name.length > MAX_PASTED_IMAGE_NAME_CHARS) {
+ return post({ type: 'paste-image-failed', requestId, index });
+ }
+ const reader = new FileReader();
+ reader.onload = () => {
+ const result = String(reader.result || '');
+ const comma = result.indexOf(',');
+ const base64 = comma >= 0 ? result.slice(comma + 1) : '';
+ if (!base64 || base64.length > MAX_PASTED_IMAGE_BASE64_CHARS) {
+ post({ type: 'paste-image-failed', requestId, index });
+ return;
+ }
+ post({
+ type: 'paste-image', requestId, index, mimeType, name, base64,
+ });
+ };
+ reader.onerror = () => post({ type: 'paste-image-failed', requestId, index });
+ reader.readAsDataURL(file);
+ });
+ return;
+ }
+ event.preventDefault();
+ const requestId = createPasteMarker();
+ if (!requestId) return;
+ const clipboardText = event.clipboardData && event.clipboardData.getData('text/plain') || '';
+ const text = clipboardText.length <= 4000000 ? clipboardText || undefined : undefined;
+ post({ type: 'paste-text-request', requestId, text });
+ });
+
+ root.addEventListener('mousedown', (event) => {
+ const atom = event.target && event.target.closest && event.target.closest('.atom');
+ if (!atom) return;
+ event.preventDefault();
+ placeCaretAroundAtom(atom, event.clientX);
+ });
+ root.addEventListener('touchstart', (event) => {
+ const atom = event.target && event.target.closest && event.target.closest('.atom');
+ const touch = event.touches && event.touches[0];
+ if (!atom || !touch) return;
+ event.preventDefault();
+ placeCaretAroundAtom(atom, touch.clientX);
+ }, { passive: false });
+
+ window.cindyComposer = {
+ applyDocument(value, focusAfter) { render(value, focusAfter === true); },
+ focus() { placeCaretAtEnd(); },
+ blur() { root.blur(); },
+ insertNode(node) { insertAtSelection(node); },
+ commitPaste(requestId, nodes) { commitPaste(requestId, nodes); },
+ resolveSessionLink(href, label) { resolveSessionLink(href, label); },
+ setConfig(value) { applyConfig(value || {}); reportHeight(); },
+ };
+ new ResizeObserver(reportHeight).observe(root);
+ render(config.document, false);
+ post({ type: 'ready' });
+})();
+</script></body></html>`;
+}
diff --git a/apps/mobile/src/session/composerRichInputProtocol.ts b/apps/mobile/src/session/composerRichInputProtocol.ts
new file mode 100644
index 0000000000..47b2e54053
--- /dev/null
+++ b/apps/mobile/src/session/composerRichInputProtocol.ts
@@ -0,0 +1,110 @@
+export type ComposerWebMessage =
+ | { type: 'ready' | 'focus' | 'blur' }
+ | { type: 'height'; height: number }
+ | { type: 'change'; document: unknown }
+ | { type: 'paste-text-request'; requestId: string; text?: string }
+ | { type: 'paste-images-start'; requestId: string; count: number }
+ | { type: 'paste-image'; requestId: string; base64: string; mimeType: string; name: string; index: number }
+ | { type: 'paste-image-failed'; requestId: string; index: number };
+
+export const MAX_PASTED_IMAGE_COUNT = 20;
+export const MAX_PASTED_IMAGE_BASE64_CHARS = 40_000_000;
+export const MAX_PASTED_IMAGE_NAME_CHARS = 255;
+export const MAX_PASTED_TEXT_CHARS = 4_000_000;
+const MAX_PASTE_REQUEST_ID_CHARS = 64;
+export const SUPPORTED_PASTED_IMAGE_MIME_TYPES = [
+ 'image/gif',
+ 'image/heic',
+ 'image/heif',
+ 'image/jpeg',
+ 'image/png',
+ 'image/webp',
+] as const;
+const SUPPORTED_PASTED_IMAGE_MIME_TYPE_SET = new Set<string>(
+ SUPPORTED_PASTED_IMAGE_MIME_TYPES,
+);
+
+/** Parse the untrusted WebView bridge payload into the small native protocol. */
+export function parseComposerWebMessage(raw: string): ComposerWebMessage | null {
+ try {
+ const value: unknown = JSON.parse(raw);
+ if (!value || typeof value !== 'object') return null;
+ const message = value as Record<string, unknown>;
+ if (
+ message.type === 'ready'
+ || message.type === 'focus'
+ || message.type === 'blur'
+ ) return { type: message.type };
+ if (message.type === 'height') {
+ return typeof message.height === 'number' && Number.isFinite(message.height)
+ ? { type: 'height', height: message.height }
+ : null;
+ }
+ if (message.type === 'change') {
+ return { type: 'change', document: message.document };
+ }
+ if (message.type === 'paste-text-request') {
+ if (
+ typeof message.requestId !== 'string'
+ || message.requestId.length === 0
+ || message.requestId.length > MAX_PASTE_REQUEST_ID_CHARS
+ || (message.text !== undefined && (
+ typeof message.text !== 'string'
+ || message.text.length > MAX_PASTED_TEXT_CHARS
+ ))
+ ) return null;
+ return {
+ type: 'paste-text-request',
+ requestId: message.requestId,
+ ...(typeof message.text === 'string' ? { text: message.text } : {}),
+ };
+ }
+ if (message.type === 'paste-images-start') {
+ return isValidRequestId(message.requestId) && isBoundedImageIndex(message.count, 1)
+ ? { type: 'paste-images-start', requestId: message.requestId, count: message.count }
+ : null;
+ }
+ if (message.type === 'paste-image-failed') {
+ return isValidRequestId(message.requestId) && isBoundedImageIndex(message.index, 0)
+ ? { type: 'paste-image-failed', requestId: message.requestId, index: message.index }
+ : null;
+ }
+ if (message.type === 'paste-image') {
+ if (
+ !isValidRequestId(message.requestId)
+ || typeof message.base64 !== 'string'
+ || message.base64.length === 0
+ || message.base64.length > MAX_PASTED_IMAGE_BASE64_CHARS
+ || typeof message.mimeType !== 'string'
+ || !SUPPORTED_PASTED_IMAGE_MIME_TYPE_SET.has(message.mimeType)
+ || typeof message.name !== 'string'
+ || message.name.length > MAX_PASTED_IMAGE_NAME_CHARS
+ || !isBoundedImageIndex(message.index, 0)
+ ) return null;
+ return {
+ type: 'paste-image',
+ requestId: message.requestId,
+ base64: message.base64,
+ mimeType: message.mimeType,
+ name: message.name,
+ index: message.index,
+ };
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+function isValidRequestId(value: unknown): value is string {
+ return typeof value === 'string'
+ && value.length > 0
+ && value.length <= MAX_PASTE_REQUEST_ID_CHARS;
+}
+
+function isBoundedImageIndex(value: unknown, minimum: number): value is number {
+ return typeof value === 'number'
+ && Number.isSafeInteger(value)
+ && value >= minimum
+ && value <= MAX_PASTED_IMAGE_COUNT;
+}
diff --git a/apps/mobile/src/session/fileBrowserActions.ts b/apps/mobile/src/session/fileBrowserActions.ts
index 5379519087..94b6996e54 100644
--- a/apps/mobile/src/session/fileBrowserActions.ts
+++ b/apps/mobile/src/session/fileBrowserActions.ts
@@ -3,7 +3,18 @@
*/
import { ungzip } from 'pako';
-import { readComposerDraftSync, saveComposerDraft } from '@/session/composerDraftStore';
+import {
+ readComposerDocumentDraftSync,
+ readComposerDraftSync,
+ saveComposerDocumentDraft,
+ saveComposerDraft,
+} from '@/session/composerDraftStore';
+import {
+ appendComposerNode,
+ composerDocumentProjectedText,
+ mentionComposerNode,
+ textComposerDocument,
+} from '@/session/composerDocument';
import { serializeAtResource } from '@/session/composerPalette';
import { imageMimeFromUrl } from '@/session/remoteMediaDiskCache';
@@ -53,9 +64,17 @@ export function mergePathIntoComposerDraft(
const existing = readComposerDraftSync(sessionId) ?? '';
const token = serializeAtResource({ type: kind, relPath });
if (existing.includes(token)) return existing;
- const merged = existing.length === 0
- ? `${token} `
- : `${existing.endsWith(' ') || existing.endsWith('\n') ? existing : `${existing} `}${token} `;
+ const currentDocument = readComposerDocumentDraftSync(sessionId) ?? textComposerDocument(existing);
+ const separated = existing.length > 0 && !existing.endsWith(' ') && !existing.endsWith('\n')
+ ? appendComposerNode(currentDocument, { type: 'text', text: ' ' })
+ : currentDocument;
+ const withMention = appendComposerNode(
+ separated,
+ mentionComposerNode({ type: kind, relPath }),
+ );
+ const mergedDocument = appendComposerNode(withMention, { type: 'text', text: ' ' });
+ const merged = composerDocumentProjectedText(mergedDocument);
+ saveComposerDocumentDraft(sessionId, mergedDocument);
saveComposerDraft(sessionId, merged);
return merged;
}
diff --git a/apps/mobile/src/session/inputProjection.ts b/apps/mobile/src/session/inputProjection.ts
index 53adc07c5d..927a776459 100644
--- a/apps/mobile/src/session/inputProjection.ts
+++ b/apps/mobile/src/session/inputProjection.ts
@@ -3,9 +3,24 @@ import {
buildAttachmentPersistImageRefs,
} from '@/session/attachments';
import { stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';
+import {
+ readAgentInputReferences,
+ type AgentInputReference,
+} from '@cindy/maker-shared/agent-input-projection';
import type { InputProjection, QueuedRemoteMessage, RemoteImageRef, RemoteSession } from '@/session/types';
import type { RemoteSerializedAttachment } from '@/session/types';
import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';
+import {
+ composerDocumentsEqual,
+ composerDocumentFromSerializedMessage,
+ composerDocumentProjectedText,
+ serializeComposerDocument,
+ type ComposerDocument,
+} from '@/session/composerDocument';
+import {
+ readSentPastedTextRanges,
+ readSentSlashCommandRanges,
+} from '@/session/sentMessageAtoms';
export {
buildQueuePanelSummary,
buildQueueRowPresentation,
@@ -74,6 +89,9 @@ export function buildQueuedTextMessage(
options: {
attachments?: readonly RemoteSerializedAttachment[];
quotesEncoded?: boolean;
+ agentReferences?: AgentInputReference[];
+ pastedTextRanges?: Array<{ start: number; end: number; display: string }>;
+ slashCommandRanges?: Array<{ start: number; end: number }>;
} = {},
): QueuedRemoteMessage {
const trimmed = text.trim();
@@ -89,6 +107,9 @@ export function buildQueuedTextMessage(
persistedImageRefs,
persistedFileRefs,
options.quotesEncoded === true,
+ options.pastedTextRanges,
+ options.slashCommandRanges,
+ options.agentReferences,
);
const createdAt = now.toISOString();
@@ -97,6 +118,7 @@ export function buildQueuedTextMessage(
text: trimmed,
persistedContent,
...(attachments.length > 0 ? { files: [...attachments] } : {}),
+ ...(options.agentReferences?.length ? { agentReferences: options.agentReferences } : {}),
model: session.model,
effort,
permissionMode,
@@ -108,6 +130,8 @@ export function buildQueuedTextMessage(
...(persistedImageRefs.length > 0 ? { images: persistedImageRefs } : {}),
...(persistedFileRefs.length > 0 ? { files: persistedFileRefs } : {}),
...(options.quotesEncoded === true ? { quotesEncoded: true } : {}),
+ ...(options.pastedTextRanges?.length ? { pastedTextRanges: options.pastedTextRanges } : {}),
+ ...(options.slashCommandRanges !== undefined ? { slashCommandRanges: options.slashCommandRanges } : {}),
isStreaming: false,
createdAt,
},
@@ -137,12 +161,18 @@ function stringifyUserContent(
images: RemoteImageRef[] = [],
files: Array<{ name: string; path: string }> = [],
quotesEncoded = false,
+ pastedTextRanges: Array<{ start: number; end: number; display: string }> = [],
+ slashCommandRanges?: Array<{ start: number; end: number }>,
+ agentReferences: AgentInputReference[] = [],
): string {
return JSON.stringify({
text,
images,
files,
...(quotesEncoded ? { quotesEncoded: true } : {}),
+ ...(pastedTextRanges.length > 0 ? { pastedTextRanges } : {}),
+ ...(slashCommandRanges !== undefined ? { slashCommandRanges } : {}),
+ ...(agentReferences.length > 0 ? { agentReferences } : {}),
});
}
@@ -162,34 +192,90 @@ export interface QueueEditTextState {
visibleText: string;
encodedText: string;
quotesEncoded: boolean;
+ document: ComposerDocument;
+ pastedTextRanges: Array<{ start: number; end: number; display: string }>;
+ slashCommandRanges: Array<{ start: number; end: number }> | undefined;
+ agentReferences: AgentInputReference[];
}
export function createQueueEditTextState(
message: Pick<QueuedRemoteMessage, 'text' | 'persistedContent'>,
): QueueEditTextState {
const quotesEncoded = queuedMessageHasEncodedQuotes(message);
+ const metadata = readQueuedTextMetadata(message.persistedContent, message.text);
+ const document = composerDocumentFromSerializedMessage(message.text, {
+ quotesEncoded,
+ agentReferences: metadata.agentReferences,
+ pastedTextRanges: metadata.pastedTextRanges,
+ slashCommandRanges: metadata.slashCommandRanges,
+ });
return {
- visibleText: quotesEncoded ? stripChatQuoteMarkerLines(message.text) : message.text,
+ visibleText: composerDocumentProjectedText(document),
encodedText: message.text,
quotesEncoded,
+ document,
+ pastedTextRanges: metadata.pastedTextRanges,
+ slashCommandRanges: metadata.slashCommandRanges,
+ agentReferences: metadata.agentReferences,
};
}
/**
- * 引用消息可见文本未改时复用原 marked body;一旦用户编辑 markerless 文本,
- * 就同步移除 quotesEncoded,避免普通 Markdown blockquote 被误还原成产品引用。
+ * 文档未改时复用原持久化正文与 metadata;修改后从结构化文档重新序列化,
+ * 保留仍存在的引用 / 粘贴文本 / Slash atom,删除的 atom 则自然退出 metadata。
*/
export function resolveQueueEditTextSubmission(
state: QueueEditTextState,
- visibleText: string,
-): { text: string; quotesEncoded: boolean } {
- const preserveEncodedBody = state.quotesEncoded && visibleText === state.visibleText;
+ document: ComposerDocument,
+): {
+ text: string;
+ quotesEncoded: boolean;
+ pastedTextRanges?: Array<{ start: number; end: number; display: string }>;
+ slashCommandRanges?: Array<{ start: number; end: number }>;
+ agentReferences: AgentInputReference[];
+} {
+ const documentUnchanged = composerDocumentsEqual(document, state.document);
+ if (!documentUnchanged) {
+ const serialized = serializeComposerDocument(document);
+ return {
+ text: serialized.text,
+ quotesEncoded: serialized.quotesEncoded,
+ agentReferences: serialized.agentReferences,
+ ...(serialized.pastedTextRanges.length > 0
+ ? { pastedTextRanges: serialized.pastedTextRanges }
+ : {}),
+ slashCommandRanges: serialized.slashCommandRanges,
+ };
+ }
return {
- text: preserveEncodedBody ? state.encodedText : visibleText.trim(),
- quotesEncoded: preserveEncodedBody,
+ text: state.encodedText,
+ quotesEncoded: state.quotesEncoded,
+ agentReferences: state.agentReferences,
+ ...(state.pastedTextRanges.length > 0
+ ? { pastedTextRanges: state.pastedTextRanges }
+ : {}),
+ ...(state.slashCommandRanges !== undefined
+ ? { slashCommandRanges: state.slashCommandRanges }
+ : {}),
};
}
+function readQueuedTextMetadata(persistedContent: string, text: string): {
+ pastedTextRanges: Array<{ start: number; end: number; display: string }>;
+ slashCommandRanges: Array<{ start: number; end: number }> | undefined;
+ agentReferences: AgentInputReference[];
+} {
+ try {
+ const record = readRecord(JSON.parse(persistedContent));
+ const pastedTextRanges = readSentPastedTextRanges(record?.pastedTextRanges, text) ?? [];
+ const slashCommandRanges = readSentSlashCommandRanges(record?.slashCommandRanges, text);
+ const agentReferences = readAgentInputReferences(record?.agentReferences, text);
+ return { pastedTextRanges, slashCommandRanges, agentReferences };
+ } catch {
+ return { pastedTextRanges: [], slashCommandRanges: undefined, agentReferences: [] };
+ }
+}
+
function readQueuedMessages(value: unknown): QueuedRemoteMessage[] {
if (!Array.isArray(value)) return [];
const out: QueuedRemoteMessage[] = [];
diff --git a/apps/mobile/src/session/messageActionMenu.ts b/apps/mobile/src/session/messageActionMenu.ts
new file mode 100644
index 0000000000..2aa5656526
--- /dev/null
+++ b/apps/mobile/src/session/messageActionMenu.ts
@@ -0,0 +1,32 @@
+/** Pure menu model shared by the message action sheet and tests. */
+export type MobileMessageMenuActionId = 'fork' | 'add-to-chat' | 'copy-link' | 'rewind' | 'delete';
+
+export interface MobileMessageMenuItem {
+ id: MobileMessageMenuActionId;
+ label: string;
+ destructive?: boolean;
+ separatorBefore?: boolean;
+}
+
+export function buildMobileMessageMenu(input: {
+ canAddToChat: boolean;
+ canCopyLink: boolean;
+ canDelete: boolean;
+ canFork: boolean;
+ canRewind: boolean;
+}): MobileMessageMenuItem[] {
+ const items: MobileMessageMenuItem[] = [];
+ if (input.canFork) items.push({ id: 'fork', label: '在新对话中继续' });
+ if (input.canAddToChat) items.push({ id: 'add-to-chat', label: '添加到对话' });
+ if (input.canCopyLink) items.push({ id: 'copy-link', label: '复制当前对话链接' });
+ if (input.canRewind) items.push({ id: 'rewind', label: '回到此处' });
+ if (input.canDelete) {
+ items.push({
+ id: 'delete',
+ label: '删除本条对话',
+ destructive: true,
+ separatorBefore: items.length > 0,
+ });
+ }
+ return items;
+}
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index ecfd5e639a..68be33499b 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -25,6 +25,14 @@ import {
parseMobilePersistedSessionReferenceMetadata,
type MobilePersistedSessionReferenceMetadata,
} from '@/session/sessionReferences';
+import {
+ readSentPastedTextRanges,
+ readSentSlashCommandRanges,
+} from '@/session/sentMessageAtoms';
+import {
+ readAgentInputReferences,
+ type AgentInputReference,
+} from '@cindy/maker-shared/agent-input-projection';
export type NormalizedRemoteMessageKind =
| 'user'
@@ -44,6 +52,12 @@ export interface NormalizedRemoteMessage {
body: string;
/** user 消息正文包含产品引用编码;驱动跨端 marker/legacy 解析。 */
quotesEncoded?: boolean;
+ /** user 长文本粘贴原子的精确 wire ranges;正文仍保留完整 Agent payload。 */
+ pastedTextRanges?: Array<{ start: number; end: number; display: string }>;
+ /** user Composer 确认过的 Slash ranges;空数组用于关闭历史启发式。 */
+ slashCommandRanges?: Array<{ start: number; end: number }>;
+ /** user Composer 的结构化语义引用;用于 fork / rewind 恢复同款 chip。 */
+ agentReferences?: AgentInputReference[];
secondaryBody?: string;
systemCardData?: Record<string, unknown>;
systemCardType?: MobileSystemCardType;
@@ -332,6 +346,15 @@ export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): Nor
attachments: userContent?.attachments,
...(userContent?.quotesEncoded === true ? { quotesEncoded: true } : {}),
sessionReferences: userContent?.sessionReferences,
+ ...(userContent?.pastedTextRanges?.length
+ ? { pastedTextRanges: userContent.pastedTextRanges }
+ : {}),
+ ...(userContent?.slashCommandRanges !== undefined
+ ? { slashCommandRanges: userContent.slashCommandRanges }
+ : {}),
+ ...(userContent?.agentReferences?.length
+ ? { agentReferences: userContent.agentReferences }
+ : {}),
align: message.role === 'user' && hookSource === undefined ? 'user' : 'agent',
createdAt: message.createdAt,
isStreaming: readMessageStreaming(message) || undefined,
@@ -372,6 +395,9 @@ function parseUserContent(content: unknown): {
attachments: NormalizedAttachment[];
quotesEncoded: boolean;
sessionReferences: MobilePersistedSessionReferenceMetadata[];
+ pastedTextRanges?: Array<{ start: number; end: number; display: string }>;
+ slashCommandRanges?: Array<{ start: number; end: number }>;
+ agentReferences?: AgentInputReference[];
} {
const parsed = parseMaybeJsonObject(content);
if (!parsed) {
@@ -383,9 +409,15 @@ function parseUserContent(content: unknown): {
};
}
const text = typeof parsed.text === 'string' ? parsed.text : contentToPreview(content);
+ const pastedTextRanges = readSentPastedTextRanges(parsed.pastedTextRanges, text);
+ const slashCommandRanges = readSentSlashCommandRanges(parsed.slashCommandRanges, text);
+ const agentReferences = readAgentInputReferences(parsed.agentReferences, text);
return {
text,
quotesEncoded: parsed.quotesEncoded === true,
+ ...(pastedTextRanges ? { pastedTextRanges } : {}),
+ ...(slashCommandRanges !== undefined ? { slashCommandRanges } : {}),
+ ...(agentReferences.length > 0 ? { agentReferences } : {}),
attachments: [
...readImageAttachments(parsed.images),
...readFileAttachments(parsed.files),
diff --git a/apps/mobile/src/session/messagePayload.ts b/apps/mobile/src/session/messagePayload.ts
index f8ee5d89e8..92128a80bf 100644
--- a/apps/mobile/src/session/messagePayload.ts
+++ b/apps/mobile/src/session/messagePayload.ts
@@ -45,6 +45,7 @@ export {
buildFilePayload,
buildMermaidPayload,
buildPayloadToolDiff,
+ buildTextPayload,
extractPayloadToolResultMedia,
formatDiffPayload,
formatDiffPayloadRows,
diff --git a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
index 23b966785c..c48be2ee22 100644
--- a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
@@ -44,6 +44,12 @@ export interface MobileLocalAttachmentUploadCandidate {
>>>;
/** resolve 阶段已完成优化编码(如 HEIC 转码+缩边),跳过 preprocess 防二次有损。 */
skipPreprocess?: boolean;
+ /**
+ * 仅由明确拥有输入文件的调用方提供(当前是 WebView 粘贴落盘):
+ * controller 会把 resolve / preprocess 生成的同任务临时 uri 一并交回清理。
+ * 系统相册、相机与文件选择器的 uri 不设置此钩子,避免误删宿主管理的文件。
+ */
+ cleanupLocalUris?: (uris: readonly string[]) => Promise<void>;
/** 宿主侧溯源 id(相册 asset.id → attachment 映射用),管线不消费。 */
sourceId?: string;
/**
@@ -108,7 +114,9 @@ export interface MobileLocalAttachmentUploadDeps {
candidate: MobileLocalAttachmentUploadCandidate,
uploadedUri: string,
localId: string,
- ): void;
+ localUris: readonly string[],
+ isActive: () => boolean,
+ ): void | Promise<void>;
/** 单个失败(宿主展示错误文案);已被移除 / 丢弃的任务不会回调。localId 语义同 onUploaded。 */
onFailed(error: unknown, localId: string): void;
}
@@ -198,6 +206,8 @@ interface UploadTask {
claimed: boolean;
/** in-flight 取消通道:remove / removeAll / dispose 时 abort,真正断掉 PUT 传输。 */
abort: AbortController;
+ /** 本任务已接触的自有临时 uri;无 cleanupLocalUris 时只记账、不做删除。 */
+ localUris: Set<string>;
outcome: Promise<TaskOutcome>;
resolveOutcome: (outcome: TaskOutcome) => void;
}
@@ -246,6 +256,15 @@ export function createMobileLocalAttachmentUploadController(
}
}
+ function cleanupTaskLocalUris(task: UploadTask, keepOriginal: boolean): void {
+ const cleanup = task.candidate.cleanupLocalUris;
+ if (!cleanup) return;
+ const originalUri = task.candidate.uri;
+ const uris = [...task.localUris].filter((uri) => !keepOriginal || uri !== originalUri);
+ task.localUris = keepOriginal ? new Set([originalUri]) : new Set();
+ if (uris.length > 0) void cleanup(uris).catch(() => undefined);
+ }
+
async function runTask(task: UploadTask): Promise<void> {
// 先让出一拍:保证任务至少异步落定——pending 帧可见、waitForIdle 统计口径一致,
// 同步 throw(如已知 size 的超限校验)不会在 enqueue 调用栈里就把任务清掉。
@@ -269,6 +288,7 @@ export function createMobileLocalAttachmentUploadController(
if (source.resolve) {
source = { ...source, ...(await source.resolve()) };
}
+ task.localUris.add(source.uri);
// 只有图片需要降采样;文件(pdf / office / 文本)与已优化产物原样直传。
const prepared = source.kind === 'image' && !source.skipPreprocess
? await deps.preprocess({
@@ -285,6 +305,7 @@ export function createMobileLocalAttachmentUploadController(
mimeType: source.mimeType,
size: source.size,
};
+ task.localUris.add(prepared.uri);
const size = prepared.size > 0 ? prepared.size : await deps.statSize(prepared.uri);
deps.assertSize(size, task.candidate);
// 取消检查点 2:资产就位 / 降采样(大图慢路径)期间被 X 掉的任务在发起 PUT 前短路
@@ -306,8 +327,22 @@ export function createMobileLocalAttachmentUploadController(
// 回传就位后的 candidate(kind / sourceId 随 spread 保留):resolve 型任务
// (相册 ph:// 换址、HEIC / 粘贴转码)实际上传的是 source.uri,宿主的预览
// 映射要指向这个仍然在世的 file://,而不是可能被系统回收的原始临时文件。
- deps.onUploaded(attachment, source, prepared.uri, task.localId);
- outcome = 'uploaded';
+ await deps.onUploaded(
+ attachment,
+ source,
+ prepared.uri,
+ task.localId,
+ [...task.localUris],
+ () => !disposed && !task.discarded,
+ );
+ if (disposed || task.discarded) {
+ // onUploaded 可能为粘贴图片等待持久缩略图;等待期间退屏 / removeAll
+ // 时不能再把附件写回旧页面,且已经上传的 OSS 对象仍须回收。
+ deps.discard(attachment);
+ outcome = 'discarded';
+ } else {
+ outcome = 'uploaded';
+ }
}
} catch (err) {
if (task.discarded) {
@@ -320,8 +355,13 @@ export function createMobileLocalAttachmentUploadController(
if (outcome === 'failed' && !disposed) {
// 失败卡保留在托盘(state=failed,可 retry / remove),不再从 map 删除——
// 弱网下「图直接消失 + 一条 toast」逼用户重新找图重选,原地重试才是对的。
+ // 只保留原始粘贴文件供 retry;本轮 resolve / preprocess 中间产物立即回收。
+ cleanupTaskLocalUris(task, true);
task.state = 'failed';
} else {
+ // uploaded 的成功路径由 onUploaded 在把预览换成持久缩略图后清理;
+ // discarded 在这里回收全部自有临时文件。
+ if (outcome === 'discarded') cleanupTaskLocalUris(task, false);
tasks.delete(task.localId);
}
runningCount -= 1;
@@ -345,6 +385,7 @@ export function createMobileLocalAttachmentUploadController(
discarded: false,
claimed: false,
abort: new AbortController(),
+ localUris: new Set([candidate.uri]),
...createOutcome(),
});
}
@@ -356,9 +397,9 @@ export function createMobileLocalAttachmentUploadController(
const task = tasks.get(localId);
if (!task || task.discarded) return;
if (task.state === 'queued' || task.state === 'failed') {
- // 还没开跑 / 已失败结算:直接出队,没有任何需要回收的东西
- // (失败任务没有产出 OSS 对象,outcome 也已落定)。
+ // 还没开跑 / 已失败结算:直接出队;自有粘贴临时文件同步进入回收队列。
tasks.delete(task.localId);
+ cleanupTaskLocalUris(task, false);
task.resolveOutcome('discarded');
} else {
// 已 in-flight:标记丢弃 + abort 真正断掉传输(PUT 层监听 signal 走
@@ -399,6 +440,7 @@ export function createMobileLocalAttachmentUploadController(
if (task.claimed) continue;
if (task.state === 'queued' || task.state === 'failed') {
tasks.delete(task.localId);
+ cleanupTaskLocalUris(task, false);
} else {
task.discarded = true;
task.abort.abort();
@@ -482,6 +524,7 @@ export function createMobileLocalAttachmentUploadController(
for (const task of tasks.values()) {
if (task.state === 'queued' || task.state === 'failed') {
tasks.delete(task.localId);
+ cleanupTaskLocalUris(task, false);
} else {
task.discarded = true;
task.abort.abort();
diff --git a/apps/mobile/src/session/pastedImageAttachment.ts b/apps/mobile/src/session/pastedImageAttachment.ts
index 03ab7174ab..8e5b41e907 100644
--- a/apps/mobile/src/session/pastedImageAttachment.ts
+++ b/apps/mobile/src/session/pastedImageAttachment.ts
@@ -1,5 +1,5 @@
/**
- * 粘贴图片附件解析:把 expo-paste-input 抛出的剪贴板临时文件 uri 解析成
+ * 粘贴图片附件解析:把 ComposerRichInput 从 WebView 剪贴板落盘的临时文件 uri 解析成
* 可直接走现有上传链路(buildMobileImageAttachmentCandidate →
* uploadMobileAttachmentFromFile)的 { uri, fileName }。
*
@@ -11,6 +11,7 @@ import { extractRemoteFileExt } from '@/session/attachments';
/** 与 useContextSheetMediaAssets 同口径:iOS 原生格式,白名单与下游模型接口都不收。 */
const PASTED_JPEG_COMPRESS = 0.9;
+export const COMPOSER_PASTED_IMAGE_FILE_PREFIX = 'cindy-composer-paste-';
const WHITELISTED_IMAGE_EXTS = ['jpg', 'jpeg', 'png', 'gif', 'webp'] as const;
@@ -60,6 +61,11 @@ export function buildPastedImageFileName(index: number, ext: string): string {
return `pasted-image-${index + 1}.${ext}`;
}
+/** 只识别 ComposerRichInput 明确创建、应由本链路负责回收的缓存文件。 */
+export function isComposerPastedImageUri(uri: string): boolean {
+ return basenameFromUri(uri).startsWith(COMPOSER_PASTED_IMAGE_FILE_PREFIX);
+}
+
/**
* 把粘贴 uri 解析为可上传 asset。默认转换器走 expo-image-manipulator
* (lazy import,保证本模块在 vitest node 环境可导入,测试路径经 deps 注入)。
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 5952a4df3d..fba68c21dd 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -2164,14 +2164,19 @@ export function useRemoteSessions(): RemoteSession[] {
return useSyncExternalStore(remoteSessionStore.subscribe, remoteSessionStore.getSessions);
}
+/** Subscribe to one session's message mirror without triggering cache hydration side effects. */
+export function useRemoteSessionMessages(sessionId: string): RemoteMessage[] {
+ return useSyncExternalStore(
+ remoteSessionStore.subscribe,
+ () => remoteSessionStore.getMessages(sessionId),
+ );
+}
+
// 本地「最近消息」缓存持久化的去抖间隔:消息流式更新很频繁,只在静默一小段后落盘一次。
const SESSION_MESSAGE_CACHE_PERSIST_DEBOUNCE_MS = 600;
export function useSessionMessages(sessionId: string, deviceId?: string): RemoteMessage[] {
- const messages = useSyncExternalStore(
- remoteSessionStore.subscribe,
- () => remoteSessionStore.getMessages(sessionId),
- );
+ const messages = useRemoteSessionMessages(sessionId);
useSessionMessageCacheSync(sessionId, deviceId, messages);
return messages;
}
diff --git a/apps/mobile/src/session/rewindPreview.ts b/apps/mobile/src/session/rewindPreview.ts
index 9f87d8b60f..9419177dc8 100644
--- a/apps/mobile/src/session/rewindPreview.ts
+++ b/apps/mobile/src/session/rewindPreview.ts
@@ -1,4 +1,5 @@
import type { ChatQuote } from '@cindy/maker-shared/chat-quotes';
+import type { ComposerDocument } from '@/session/composerDocument';
export interface RewindPreviewPayload {
canRewind: boolean;
@@ -16,6 +17,7 @@ export type RewindPreviewState =
draftText: string;
draftQuotes: readonly ChatQuote[];
draftOrderedBody?: string;
+ draftDocument?: ComposerDocument;
}
| {
kind: 'default';
@@ -23,6 +25,7 @@ export type RewindPreviewState =
draftText: string;
draftQuotes: readonly ChatQuote[];
draftOrderedBody?: string;
+ draftDocument?: ComposerDocument;
filesChanged: string[];
insertions: number;
deletions: number;
@@ -33,6 +36,7 @@ export type RewindPreviewState =
draftText: string;
draftQuotes: readonly ChatQuote[];
draftOrderedBody?: string;
+ draftDocument?: ComposerDocument;
note?: string;
}
| {
@@ -41,6 +45,7 @@ export type RewindPreviewState =
draftText: string;
draftQuotes: readonly ChatQuote[];
draftOrderedBody?: string;
+ draftDocument?: ComposerDocument;
errorText: string;
};
@@ -52,8 +57,10 @@ export function buildRewindPreviewState(
raw: unknown,
draftQuotes: readonly ChatQuote[] = [],
draftOrderedBody?: string,
+ draftDocument?: ComposerDocument,
): RewindPreviewState {
const orderedDraft = draftOrderedBody ? { draftOrderedBody } : {};
+ const documentDraft = draftDocument ? { draftDocument } : {};
const payload = normalizeRewindPreviewPayload(raw);
if (!payload) {
return {
@@ -62,6 +69,7 @@ export function buildRewindPreviewState(
draftText,
draftQuotes,
...orderedDraft,
+ ...documentDraft,
errorText: '无法读取回退预览结果,请重新同步后再试。',
};
}
@@ -74,6 +82,7 @@ export function buildRewindPreviewState(
draftText,
draftQuotes,
...orderedDraft,
+ ...documentDraft,
filesChanged: files,
insertions: payload.insertions ?? 0,
deletions: payload.deletions ?? 0,
@@ -81,7 +90,7 @@ export function buildRewindPreviewState(
}
if (payload.canRewind) {
- return { kind: 'empty', clientId, draftText, draftQuotes, ...orderedDraft };
+ return { kind: 'empty', clientId, draftText, draftQuotes, ...orderedDraft, ...documentDraft };
}
return {
@@ -90,6 +99,7 @@ export function buildRewindPreviewState(
draftText,
draftQuotes,
...orderedDraft,
+ ...documentDraft,
note: payload.error || '没有可回滚的文件,将只截断这条消息之后的对话历史。',
};
}
diff --git a/apps/mobile/src/session/sentMessageAtoms.ts b/apps/mobile/src/session/sentMessageAtoms.ts
new file mode 100644
index 0000000000..343ddd326c
--- /dev/null
+++ b/apps/mobile/src/session/sentMessageAtoms.ts
@@ -0,0 +1,197 @@
+import {
+ formatQuoteForSend,
+ type ChatQuote,
+ type ChatQuoteSegment,
+} from '@cindy/maker-shared/chat-quotes';
+
+export interface SentPastedTextRange {
+ start: number;
+ end: number;
+ display: string;
+}
+
+export interface SentSlashCommandRange {
+ start: number;
+ end: number;
+}
+
+export function readSentPastedTextRanges(
+ value: unknown,
+ text: string,
+): SentPastedTextRange[] | undefined {
+ if (!Array.isArray(value) || value.length === 0) return undefined;
+ const ranges: SentPastedTextRange[] = [];
+ let previousEnd = 0;
+ for (const candidate of value) {
+ const range = readRangeRecord(candidate);
+ if (
+ !range
+ || !Number.isSafeInteger(range.start)
+ || !Number.isSafeInteger(range.end)
+ || typeof range.display !== 'string'
+ || !range.display
+ ) return undefined;
+ const start = Number(range.start);
+ const end = Number(range.end);
+ if (start < previousEnd || start < 0 || end <= start || end > text.length) return undefined;
+ ranges.push({ start, end, display: range.display });
+ previousEnd = end;
+ }
+ return ranges;
+}
+
+export function readSentSlashCommandRanges(
+ value: unknown,
+ text: string,
+): SentSlashCommandRange[] | undefined {
+ if (!Array.isArray(value)) return undefined;
+ const ranges: SentSlashCommandRange[] = [];
+ let previousEnd = 0;
+ for (const candidate of value) {
+ const range = readRangeRecord(candidate);
+ if (!range || !Number.isSafeInteger(range.start) || !Number.isSafeInteger(range.end)) return undefined;
+ const start = Number(range.start);
+ const end = Number(range.end);
+ if (
+ start < previousEnd
+ || start < 0
+ || end <= start
+ || end > text.length
+ || !/^\/\S+$/.test(text.slice(start, end))
+ ) return undefined;
+ ranges.push({ start, end });
+ previousEnd = end;
+ }
+ return ranges;
+}
+
+export type SentInlineToken =
+ | { kind: 'text'; text: string }
+ | { kind: 'slash'; text: string }
+ | { kind: 'pasted'; text: string; display: string }
+ | { kind: 'quote'; quote: ChatQuote };
+
+/** Split exact persisted ranges without guessing from repeated text. */
+export function buildSentInlineTokens(
+ content: string,
+ pastedTextRanges: readonly SentPastedTextRange[] = [],
+ slashCommandRanges: readonly SentSlashCommandRange[] = [],
+): SentInlineToken[] {
+ const ranges = [
+ ...pastedTextRanges.map((range) => ({ ...range, kind: 'pasted' as const })),
+ ...slashCommandRanges.map((range) => ({ ...range, kind: 'slash' as const })),
+ ].sort((a, b) => a.start - b.start || a.end - b.end);
+ const tokens: SentInlineToken[] = [];
+ let cursor = 0;
+ for (const range of ranges) {
+ if (
+ range.start < cursor
+ || range.start < 0
+ || range.end > content.length
+ || range.end <= range.start
+ ) continue;
+ if (range.start > cursor) pushTextToken(tokens, content.slice(cursor, range.start));
+ const text = content.slice(range.start, range.end);
+ if (range.kind === 'pasted') {
+ tokens.push({ kind: 'pasted', text, display: range.display });
+ } else {
+ tokens.push({ kind: 'slash', text });
+ }
+ cursor = range.end;
+ }
+ if (cursor < content.length) pushTextToken(tokens, content.slice(cursor));
+ return tokens;
+}
+
+/** Locate each parsed text island in the original quote wire text. */
+export function locateChatQuoteTextSegmentStarts(
+ content: string,
+ segments: readonly ChatQuoteSegment[],
+): Array<number | null> {
+ let cursor = 0;
+ return segments.map((segment) => {
+ if (segment.kind === 'quote') {
+ const encoded = formatQuoteForSend(segment.quote);
+ const start = content.indexOf(encoded, cursor);
+ if (start >= 0) cursor = start + encoded.length;
+ return null;
+ }
+ const start = content.indexOf(segment.text, cursor);
+ if (start < 0) return null;
+ cursor = start + segment.text.length;
+ return start;
+ });
+}
+
+export function projectSentRanges<T extends { start: number; end: number }>(
+ ranges: readonly T[],
+ sourceStart: number | null,
+ textLength: number,
+): T[] {
+ if (sourceStart === null) return [];
+ const sourceEnd = sourceStart + textLength;
+ return ranges
+ .filter((range) => range.start >= sourceStart && range.end <= sourceEnd)
+ .map((range) => ({
+ ...range,
+ start: range.start - sourceStart,
+ end: range.end - sourceStart,
+ }));
+}
+
+/**
+ * Replace quote wire blocks with quote tokens while preserving atom ranges
+ * inside every text island. Keeping every segment in one ordered stream is
+ * what lets sent messages render `quote A -> reply A -> quote B -> reply B`.
+ */
+export function buildVisibleSentInlineTokens(
+ source: string,
+ segments: readonly ChatQuoteSegment[],
+ pastedTextRanges: readonly SentPastedTextRange[] = [],
+ slashCommandRanges: readonly SentSlashCommandRange[] = [],
+): SentInlineToken[] {
+ if (segments.length === 0) return buildSentInlineTokens(source, pastedTextRanges, slashCommandRanges);
+ const starts = locateChatQuoteTextSegmentStarts(source, segments);
+ const tokens: SentInlineToken[] = [];
+ segments.forEach((segment, index) => {
+ if (segment.kind === 'quote') {
+ tokens.push({ kind: 'quote', quote: segment.quote });
+ return;
+ }
+ const sourceStart = starts[index];
+ const projectedPastes = projectSentRanges(pastedTextRanges, sourceStart, segment.text.length);
+ const projectedSlashes = projectSentRanges(slashCommandRanges, sourceStart, segment.text.length);
+ for (const token of buildSentInlineTokens(segment.text, projectedPastes, projectedSlashes)) {
+ if (token.kind === 'text') pushTextToken(tokens, token.text);
+ else tokens.push(token);
+ }
+ });
+ return tokens;
+}
+
+export function sentInlineTokensDisplayText(tokens: readonly SentInlineToken[]): string {
+ let display = '';
+ for (const token of tokens) {
+ if (token.kind === 'quote') {
+ if (display && !display.endsWith('\n')) display += '\n';
+ display += token.quote.text;
+ if (!display.endsWith('\n')) display += '\n';
+ continue;
+ }
+ display += token.kind === 'pasted' ? token.display : token.text;
+ }
+ return display.trimEnd();
+}
+
+function pushTextToken(tokens: SentInlineToken[], text: string): void {
+ if (!text) return;
+ const previous = tokens.at(-1);
+ if (previous?.kind === 'text') previous.text += text;
+ else tokens.push({ kind: 'text', text });
+}
+
+function readRangeRecord(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null;
+}
diff --git a/apps/mobile/src/session/sessionLinks.ts b/apps/mobile/src/session/sessionLinks.ts
index d74b68f0c3..76ac8d4aa3 100644
--- a/apps/mobile/src/session/sessionLinks.ts
+++ b/apps/mobile/src/session/sessionLinks.ts
@@ -88,12 +88,12 @@ export function parseSessionDeepLinkUrl(url: string): SessionDeepLinkTarget | nu
* 这里每次调用都新建实例避免共享状态。
*/
export function createSessionLinkPattern(): RegExp {
- return new RegExp(
- `(?:${DEEP_LINK_SCHEME_GROUP})://session/[A-Za-z0-9%~_-]+(?:\\?[A-Za-z0-9%&=~._-]*)?`,
- 'g',
- );
+ return new RegExp(SESSION_DEEP_LINK_RE_SOURCE, 'g');
}
+export const SESSION_DEEP_LINK_RE_SOURCE =
+ `(?:${DEEP_LINK_SCHEME_GROUP}):\\/\\/session\\/[A-Za-z0-9%~_-]+(?:\\?[A-Za-z0-9%&=~._-]*)?`;
+
/** 剥掉裸链接匹配尾部粘连的英文标点(句尾 `.` `,` 等),返回修剪后的 URL。 */
export function trimSessionLinkMatch(match: string): string {
return match.replace(/[.,;:!?]+$/, '');
@@ -126,6 +126,40 @@ export function parseProjectDeepLinkUrl(url: string): { workingDir: string } | n
return workingDir ? { workingDir } : null;
}
+export const PROJECT_DEEP_LINK_RE_SOURCE =
+ `(?:${DEEP_LINK_SCHEME_GROUP}):\\/\\/project\\/[A-Za-z0-9%~._!*-]+(?![A-Za-z0-9%~._!*('-])`;
+
+export function createProjectLinkPattern(): RegExp {
+ return new RegExp(PROJECT_DEEP_LINK_RE_SOURCE, 'g');
+}
+
+function isMarkdownEscaped(text: string, index: number): boolean {
+ let backslashes = 0;
+ for (let cursor = index - 1; cursor >= 0 && text.charCodeAt(cursor) === 92; cursor -= 1) {
+ backslashes += 1;
+ }
+ return backslashes % 2 === 1;
+}
+
+/** Locate the matching `[` for the `]` in `[label](deep-link)`. */
+export function findMarkdownLabelStart(text: string, closeBracketIndex: number): number {
+ if (isMarkdownEscaped(text, closeBracketIndex)) return -1;
+ let depth = 1;
+ for (let cursor = closeBracketIndex - 1; cursor >= 0; cursor -= 1) {
+ const code = text.charCodeAt(cursor);
+ if (code === 10) return -1;
+ if (code !== 91 && code !== 93) continue;
+ if (isMarkdownEscaped(text, cursor)) continue;
+ if (code === 93) depth += 1;
+ else if (--depth === 0) return cursor;
+ }
+ return -1;
+}
+
+export function unescapeMarkdownLabelBrackets(label: string): string {
+ return label.replace(/\\([[\]])/g, '$1');
+}
+
/** workingDir 末段目录名(POSIX / Windows 分隔符都认;取不出末段回退原串)。 */
export function projectDisplayName(workingDir: string): string {
const trimmed = workingDir.replace(/[\\/]+$/, '');
diff --git a/apps/mobile/src/session/sessionMessageText.ts b/apps/mobile/src/session/sessionMessageText.ts
new file mode 100644
index 0000000000..d70ee08cb4
--- /dev/null
+++ b/apps/mobile/src/session/sessionMessageText.ts
@@ -0,0 +1,62 @@
+import { joinChatQuoteTextSegments, parseChatQuoteSegments } from '@cindy/maker-shared/chat-quotes';
+import { normalizeRemoteMessages } from '@/session/messageNormalize';
+import {
+ createSessionLinkPattern,
+ parseSessionDeepLinkUrl,
+ trimSessionLinkMatch,
+} from '@/session/sessionLinks';
+import type { RemoteMessage } from '@/session/types';
+
+const MESSAGE_LABEL_MAX_CHARS = 240;
+
+/** Readable text only; never stringify tool/SDK metadata into a reference chip. */
+export function mobileSessionMessageDisplayText(message: RemoteMessage): string | null {
+ const normalized = normalizeRemoteMessages([message]).find((item) => (
+ item.kind === 'user' || item.kind === 'assistant'
+ ));
+ if (!normalized) return null;
+ let text = normalized.body.trim();
+ if (normalized.kind === 'user' && normalized.quotesEncoded === true) {
+ const segments = parseChatQuoteSegments(normalized.body);
+ const hasQuote = segments.some((segment) => segment.kind === 'quote');
+ if (hasQuote) text = joinChatQuoteTextSegments(segments).trim();
+ }
+ if (!text) {
+ text = (normalized.attachments ?? []).map((item) => item.name).filter(Boolean).join(' · ');
+ }
+ return text || null;
+}
+
+export function compactSessionMessageLabel(text: string): string {
+ const compact = text.replace(/\s+/g, ' ').trim();
+ if (compact.length <= MESSAGE_LABEL_MAX_CHARS) return compact;
+ return `${compact.slice(0, MESSAGE_LABEL_MAX_CHARS - 1)}…`;
+}
+
+export type AnchoredSessionMessageTextPart =
+ | { kind: 'text'; text: string }
+ | { kind: 'message-link'; url: string; sessionId: string; messageClientId: string };
+
+/** Split only message-anchored session links; whole-session links stay in normal Markdown. */
+export function splitAnchoredSessionMessageLinks(text: string): AnchoredSessionMessageTextPart[] {
+ const parts: AnchoredSessionMessageTextPart[] = [];
+ const pattern = createSessionLinkPattern();
+ let cursor = 0;
+ let match: RegExpExecArray | null;
+ while ((match = pattern.exec(text)) !== null) {
+ const url = trimSessionLinkMatch(match[0]);
+ const target = parseSessionDeepLinkUrl(url);
+ if (!target?.messageClientId) continue;
+ if (match.index > cursor) parts.push({ kind: 'text', text: text.slice(cursor, match.index) });
+ parts.push({
+ kind: 'message-link',
+ url,
+ sessionId: target.sessionId,
+ messageClientId: target.messageClientId,
+ });
+ cursor = match.index + url.length;
+ pattern.lastIndex = cursor;
+ }
+ if (cursor < text.length) parts.push({ kind: 'text', text: text.slice(cursor) });
+ return parts.length > 0 ? parts : [{ kind: 'text', text }];
+}
diff --git a/apps/mobile/src/session/sessionOutbox.ts b/apps/mobile/src/session/sessionOutbox.ts
index 1272c8acd1..83ad37c719 100644
--- a/apps/mobile/src/session/sessionOutbox.ts
+++ b/apps/mobile/src/session/sessionOutbox.ts
@@ -18,6 +18,13 @@
*/
import type { MobileSessionReference } from '@/session/sessionReferences';
import type { RemoteSerializedAttachment } from '@/session/types';
+import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
+import {
+ composerDocumentFromSerializedMessage,
+ normalizeComposerDocument,
+ type ComposerDocument,
+ type ComposerNode,
+} from '@/session/composerDocument';
import {
joinChatQuoteTextSegments,
parseChatQuoteSegments,
@@ -55,6 +62,9 @@ export interface MobileOutboxItem {
quotesEncoded: boolean;
/** 点击发送时解析出的来源设备提示;附件上传期间不得重新依赖易失的远程镜像。 */
sessionRefs?: MobileSessionReference[];
+ agentReferences: AgentInputReference[];
+ pastedTextRanges: Array<{ start: number; end: number; display: string }>;
+ slashCommandRanges: Array<{ start: number; end: number }>;
/**
* 发送时刻的权限档快照:plan 一次性语义在点发送时就恢复会话档,dispatch 重读
* store 拿到的已是恢复后的值,消息本身必须仍按发送时刻的档位派发。
@@ -115,12 +125,14 @@ export interface MobileOutboxDraftRecovery {
visibleText: string;
encodedBody: string;
quotes: ChatQuote[];
+ document: ComposerDocument;
}
export interface MobileOutboxExistingDraft {
visibleText: string;
encodedBody: string;
quotes: readonly ChatQuote[];
+ document?: ComposerDocument;
}
export function buildOutboxItem(input: {
@@ -129,6 +141,9 @@ export function buildOutboxItem(input: {
text: string;
quotesEncoded?: boolean;
sessionRefs?: readonly MobileSessionReference[];
+ agentReferences?: AgentInputReference[];
+ pastedTextRanges?: Array<{ start: number; end: number; display: string }>;
+ slashCommandRanges?: Array<{ start: number; end: number }>;
permissionModeAtSend: string;
/** 发送时刻已就绪的附件(占前段槽位)。 */
readyAttachments: readonly RemoteSerializedAttachment[];
@@ -166,6 +181,9 @@ export function buildOutboxItem(input: {
...(input.sessionRefs && input.sessionRefs.length > 0
? { sessionRefs: [...input.sessionRefs] }
: {}),
+ agentReferences: input.agentReferences ?? [],
+ pastedTextRanges: input.pastedTextRanges ?? [],
+ slashCommandRanges: input.slashCommandRanges ?? [],
permissionModeAtSend: input.permissionModeAtSend,
attachmentSlots: slots,
slotMeta,
@@ -185,11 +203,18 @@ export function recoverOutboxItemsToComposerDraft(
const visibleParts: string[] = [];
const encodedParts: string[] = [];
const quotes: ChatQuote[] = [];
+ const documents: ComposerDocument[] = [];
for (const item of items) {
const encodedText = item.text.trim();
if (!encodedText) continue;
encodedParts.push(encodedText);
+ documents.push(composerDocumentFromSerializedMessage(encodedText, {
+ quotesEncoded: item.quotesEncoded,
+ pastedTextRanges: item.pastedTextRanges,
+ slashCommandRanges: item.slashCommandRanges,
+ agentReferences: item.agentReferences,
+ }));
if (!item.quotesEncoded) {
visibleParts.push(encodedText);
continue;
@@ -217,11 +242,29 @@ export function recoverOutboxItemsToComposerDraft(
encodedParts.push(normalizedExistingEncodedBody);
}
quotes.push(...(existingDraft?.quotes ?? []));
+ if (existingDraft?.document) {
+ documents.push(existingDraft.document);
+ } else if (normalizedExistingEncodedBody) {
+ documents.push(composerDocumentFromSerializedMessage(normalizedExistingEncodedBody, {
+ quotesEncoded: (existingDraft?.quotes.length ?? 0) > 0,
+ }));
+ }
+
+ const nodes: ComposerNode[] = [];
+ documents.forEach((document, index) => {
+ const previous = nodes.at(-1);
+ const first = document.nodes[0];
+ if (index > 0 && previous?.type !== 'quote' && first?.type !== 'quote') {
+ nodes.push({ type: 'text', text: '\n\n' });
+ }
+ nodes.push(...document.nodes);
+ });
return {
visibleText: visibleParts.join('\n\n'),
encodedBody: encodedParts.join('\n\n'),
quotes,
+ document: normalizeComposerDocument({ version: 1, nodes }),
};
}
diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.ts
index 5f3069153c..af41132b8b 100644
--- a/apps/mobile/src/session/types.ts
+++ b/apps/mobile/src/session/types.ts
@@ -1,4 +1,5 @@
import type { MobileSessionAgentSwitchIntent } from '@cindy/maker-shared/device-link-contract';
+import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
export type RemoteSessionStatus = 'active' | 'archived' | 'deleted';
export type RemoteMessageRole =
@@ -154,6 +155,7 @@ export interface QueuedRemoteMessage {
text: string;
persistedContent: string;
files?: RemoteSerializedAttachment[];
+ agentReferences?: AgentInputReference[];
model: string;
effort: string;
permissionMode: string;
@@ -188,6 +190,8 @@ export interface QueuedRemoteMessage {
files?: RemoteFileRef[];
images?: RemoteImageRef[];
quotesEncoded?: boolean;
+ pastedTextRanges?: Array<{ start: number; end: number; display: string }>;
+ slashCommandRanges?: Array<{ start: number; end: number }>;
isStreaming?: boolean;
createdAt: string;
};
diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.ts
index 6ee2892c8d..a71ddd9402 100644
--- a/apps/mobile/src/session/useMobileLocalAttachments.ts
+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts
@@ -41,10 +41,14 @@ import {
import {
buildPastedImageFileName,
classifyPastedImageUri,
+ isComposerPastedImageUri,
mimeTypeForPastedImageExt,
resolvePastedImageAsset,
} from '@/session/pastedImageAttachment';
-import { registerSentAttachmentThumb } from '@/session/sentAttachmentThumbStore';
+import {
+ getSentAttachmentThumbUri,
+ registerSentAttachmentThumb,
+} from '@/session/sentAttachmentThumbStore';
import type { RemoteSerializedAttachment } from '@/session/types';
export interface UseMobileLocalAttachmentsOptions {
@@ -73,6 +77,12 @@ export interface UseMobileLocalAttachmentsOptions {
*/
const PASTE_PLACEHOLDER_TIMEOUT_MS = 60_000;
+async function deleteLocalUris(uris: readonly string[]): Promise<void> {
+ await Promise.all(uris.map((uri) => (
+ FileSystem.deleteAsync(uri, { idempotent: true }).catch(() => undefined)
+ )));
+}
+
export interface UseMobileLocalAttachmentsResult {
/** 上传中的附件(托盘渲染 pending 卡)。 */
pendingUploads: readonly PendingLocalAttachmentUpload[];
@@ -89,7 +99,7 @@ export interface UseMobileLocalAttachmentsResult {
addImages: (source: 'library' | 'camera') => Promise<void>;
/** 拉起系统文件选择器。 */
addDocument: () => Promise<void>;
- /** 输入框长按 Paste 粘贴剪贴板图片(expo-paste-input 上抛 file:// 临时文件)。 */
+ /** 输入框 Paste 粘贴剪贴板图片(ComposerRichInput 落盘的 file:// 临时文件)。 */
addPastedImages: (uris: string[]) => Promise<void>;
/** 直接入队已构造好的 candidates(Context 面板批量提交用,调用方自备 token,可传 Promise)。 */
enqueueUploads: (
@@ -131,6 +141,12 @@ export function useMobileLocalAttachments(
): UseMobileLocalAttachmentsResult {
const [pendingUploads, setPendingUploads] = useState<readonly PendingLocalAttachmentUpload[]>([]);
const pickerBusyRef = useRef(false);
+ /** 本 hook 拥有的 WebView 粘贴缓存;注册持久缩略图后或卸载时统一回收。 */
+ const pastedImageLocalUrisRef = useRef(new Set<string>());
+ const cleanupPastedImageLocalUris = async (uris: readonly string[]): Promise<void> => {
+ await deleteLocalUris(uris);
+ for (const uri of uris) pastedImageLocalUrisRef.current.delete(uri);
+ };
// 粘贴占位卡:按「批次」FIFO 记账(ref 数组是同步真源,state 只存总数供渲染
// ——与 pendingCount 同理,限额校验不能读滞后一拍的 state)。原生事件不带批次
// id,但两端的媒体处理都是串行队列(iOS mediaProcessingQueue / Android 单线程
@@ -224,21 +240,44 @@ export function useMobileLocalAttachments(
getToken: () => optionsRef.current.getAccessToken(),
}),
onPendingChange: setPendingUploads,
- onUploaded: (attachment, candidate, uploadedUri, localId) => {
+ onUploaded: async (attachment, candidate, uploadedUri, localId, localUris, isActive) => {
// 发送后气泡的本地缩略图兜底:消息里持久化的是 cindy-oss-attach:// 中转引用,
// 被控端物化改写前(乐观渲染 / 电脑离线窗口)渲染端没有任何预览路径——把
- // 实际上传的文件拷进自有目录记映射,气泡用本地图顶上。fire-and-forget,
- // 失败静默(store 内部兜),绝不挡上传回调主流程。
+ // 实际上传的文件拷进自有目录记映射,气泡用本地图顶上。
+ let deliveredCandidate = candidate;
if (candidate.kind === 'image') {
- void registerSentAttachmentThumb(attachment.url ?? attachment.path, uploadedUri || candidate.uri);
+ const ossRef = attachment.url ?? attachment.path;
+ if (candidate.cleanupLocalUris) {
+ // 粘贴源文件需要回收:先等持久缩略图完成接管,才能安全删源文件。
+ await registerSentAttachmentThumb(ossRef, uploadedUri || candidate.uri);
+ const durablePreviewUri = ossRef ? getSentAttachmentThumbUri(ossRef) : null;
+ if (durablePreviewUri) deliveredCandidate = { ...candidate, uri: durablePreviewUri };
+ } else {
+ // 相册 / 相机原有路径不拥有源文件,保持 fire-and-forget,不拉长上传落定时间。
+ void registerSentAttachmentThumb(ossRef, uploadedUri || candidate.uri);
+ }
+ }
+ if (candidate.cleanupLocalUris) {
+ for (const uri of localUris) pastedImageLocalUrisRef.current.add(uri);
+ }
+ if (!isActive()) return;
+ optionsRef.current.onUploaded(attachment, deliveredCandidate, localId);
+ if (candidate.cleanupLocalUris) {
+ // 只有持久缩略图已经接管 composer / sent-message 预览后才删源文件;
+ // 注册失败时保留到页面卸载,不能让已上传附件立刻变成坏图。
+ if (deliveredCandidate.uri !== candidate.uri) {
+ await candidate.cleanupLocalUris(localUris);
+ }
}
- optionsRef.current.onUploaded(attachment, candidate, localId);
},
onFailed: (err, localId) => optionsRef.current.onError(formatRemoteError(err), { uploadLocalId: localId }),
}), []);
useEffect(() => () => {
controller.dispose();
+ const pastedUris = [...pastedImageLocalUrisRef.current];
+ pastedImageLocalUrisRef.current.clear();
+ if (pastedUris.length > 0) void deleteLocalUris(pastedUris);
if (pastePlaceholderTimerRef.current) {
clearTimeout(pastePlaceholderTimerRef.current);
pastePlaceholderTimerRef.current = null;
@@ -367,18 +406,27 @@ export function useMobileLocalAttachments(
*/
const addPastedImages = async (uris: string[]): Promise<void> => {
if (uris.length === 0) return;
+ const ownedUris = uris.filter(isComposerPastedImageUri);
+ for (const uri of ownedUris) pastedImageLocalUrisRef.current.add(uri);
// 本批 uris 就是最早一批占位卡的兑现:先按 FIFO 出列本批再做限额检查
//(否则这批会被自己的占位双扣槽位)。出列与下方 enqueue 的 pending 上屏在
// 同一同步段,React 批处理保证占位卡 → pending 卡之间没有空帧。
shiftPastePlaceholderBatch();
const begun = beginPick();
- if (!begun) return;
+ if (!begun) {
+ void cleanupPastedImageLocalUris(ownedUris);
+ return;
+ }
try {
// 同步段就入队,绝不先 await token:粘贴没有 picker modal 遮挡,token 走网络 refresh
// 的等待窗里用户可直接点发送——任务不在队里的话 waitForIdle 立即返回,刚粘贴的图
// 会被静默丢弃(#589 用 attachmentBusy 门堵的就是这个,乐观管线用「先入队」替代)。
- controller.enqueue(uris.slice(0, begun.remainingSlots).map((uri, index) => {
+ const acceptedUris = uris.slice(0, begun.remainingSlots);
+ const rejectedUris = uris.slice(begun.remainingSlots).filter(isComposerPastedImageUri);
+ if (rejectedUris.length > 0) void cleanupPastedImageLocalUris(rejectedUris);
+ controller.enqueue(acceptedUris.map((uri, index) => {
const classified = classifyPastedImageUri(uri);
+ const ownsLocalFile = isComposerPastedImageUri(uri);
return {
kind: 'image' as const,
uri,
@@ -391,6 +439,7 @@ export function useMobileLocalAttachments(
const resolved = await resolvePastedImageAsset(uri, index);
return { uri: resolved.uri, name: resolved.fileName, mimeType: resolved.mimeType };
},
+ cleanupLocalUris: ownsLocalFile ? cleanupPastedImageLocalUris : undefined,
};
}), { token: optionsRef.current.getAccessToken() });
} catch (err) {
diff --git a/dependency-patches/README.md b/dependency-patches/README.md
index a2345fd22f..fe53f8d4a4 100644
--- a/dependency-patches/README.md
+++ b/dependency-patches/README.md
@@ -12,6 +12,7 @@
| --- | --- |
| `[email protected]` | 优化移动端粘贴图片的处理时序,将耗时的解码、压缩和写盘移出 UI 线程,并补充加载中与失败事件。 |
| `harmonyos-sans-sc-webfont-splitted` | 移除依赖按语言全局覆盖 `font-family` 的规则,由 Cindy 自己决定界面字体。 |
+| `[email protected]` | 回移 Yoga 对 `display: none` 与 `display: contents` 测量过程的布局状态修复,避免 Fabric 布局阶段因错误的 owner 关系触发断言崩溃(上游 `6fa330693fba313a2fe1121545c1efd558b60983`、`2546ce4d8219050fcd1bf432c7c830c9fd70c9af`)。移动端 iOS 通过 `expo-build-properties` 的 `buildReactNativeFromSource` 编译该补丁,不能改回预编译 RN Core。 |
| `[email protected]` | 修复 iOS 长文本渲染闪烁、布局性能、文本选择与选择手柄滚动等问题,并支持自定义选择菜单操作。 |
| `[email protected]` | 将 Cindy 的文本引用操作并入 iOS 系统选择菜单,同时保留复制、翻译等系统操作。 |
diff --git a/dependency-patches/[email protected] b/dependency-patches/[email protected]
new file mode 100644
index 0000000000..febf42d62e
--- /dev/null
+++ b/dependency-patches/[email protected]
@@ -0,0 +1,82 @@
+diff --git a/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp b/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp
+index 690efff4ac7..d3fbc5c86a1 100644
+--- a/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp
++++ b/ReactCommon/yoga/yoga/algorithm/CalculateLayout.cpp
+@@ -480,19 +480,23 @@ static void zeroOutLayoutRecursively(yoga::Node* const node) {
+ }
+ }
+
+-static void cleanupContentsNodesRecursively(yoga::Node* const node) {
++static void cleanupContentsNodesRecursively(
++ yoga::Node* const node,
++ bool didPerformLayout) {
+ if (node->hasContentsChildren()) [[unlikely]] {
+ node->cloneContentsChildrenIfNeeded();
+ for (auto child : node->getChildren()) {
+ if (child->style().display() == Display::Contents) {
+ child->getLayout() = {};
+ child->setLayoutDimension(0, Dimension::Width);
+ child->setLayoutDimension(0, Dimension::Height);
+- child->setHasNewLayout(true);
++ if (didPerformLayout) {
++ child->setHasNewLayout(true);
++ }
+ child->setDirty(false);
+ child->cloneChildrenIfNeeded();
+
+- cleanupContentsNodesRecursively(child);
++ cleanupContentsNodesRecursively(child, didPerformLayout);
+ }
+ }
+ }
+@@ -573,9 +573,11 @@ static void calculateLayoutImpl(
+ for (auto child : children) {
+ child->processDimensions();
+ if (child->style().display() == Display::None) {
+- zeroOutLayoutRecursively(child);
+- child->setHasNewLayout(true);
+- child->setDirty(false);
++ if (performLayout) {
++ zeroOutLayoutRecursively(child);
++ child->setHasNewLayout(true);
++ child->setDirty(false);
++ }
+ continue;
+ }
+ if (performLayout) {
+@@ -1319,7 +1321,7 @@ static void calculateLayoutImpl(
+
+ // Clean and update all display: contents nodes with a direct path to the
+ // current node as they will not be traversed
+- cleanupContentsNodesRecursively(node);
++ cleanupContentsNodesRecursively(node, performLayout);
+ return;
+ }
+
+@@ -1337,7 +1339,7 @@ static void calculateLayoutImpl(
+
+ // Clean and update all display: contents nodes with a direct path to the
+ // current node as they will not be traversed
+- cleanupContentsNodesRecursively(node);
++ cleanupContentsNodesRecursively(node, performLayout);
+ return;
+ }
+
+@@ -1355,7 +1357,7 @@ static void calculateLayoutImpl(
+ ownerHeight)) {
+ // Clean and update all display: contents nodes with a direct path to the
+ // current node as they will not be traversed
+- cleanupContentsNodesRecursively(node);
++ cleanupContentsNodesRecursively(node, /* didPerformLayout */ false);
+ return;
+ }
+
+@@ -1367,7 +1369,7 @@ static void calculateLayoutImpl(
+
+ // Clean and update all display: contents nodes with a direct path to the
+ // current node as they will not be traversed
+- cleanupContentsNodesRecursively(node);
++ cleanupContentsNodesRecursively(node, performLayout);
+
+ // STEP 1: CALCULATE VALUES FOR REMAINDER OF ALGORITHM
+ const FlexDirection mainAxis =
diff --git a/package.json b/package.json
index 38791f340a..dc888edb4c 100644
--- a/package.json
+++ b/package.json
@@ -56,6 +56,7 @@
},
"patchedDependencies": {
"harmonyos-sans-sc-webfont-splitted": "dependency-patches/harmonyos-sans-sc-webfont-splitted.patch",
+ "[email protected]": "dependency-patches/[email protected]",
"[email protected]": "dependency-patches/[email protected]",
"[email protected]": "dependency-patches/[email protected]",
"[email protected]": "dependency-patches/[email protected]"
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index 5143b47c62..1fd9267d1f 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -9,6 +9,7 @@
"exports": {
".": "./src/index.ts",
"./agent-capabilities": "./src/agentCapabilities.ts",
+ "./agent-input-projection": "./src/agentInputProjection.ts",
"./agent-task": "./src/agentTask.ts",
"./branding": "./src/branding.ts",
"./brand-identity": "./src/brandIdentity.ts",
diff --git a/packages/maker-shared/src/__tests__/agentInputProjection.test.ts b/packages/maker-shared/src/__tests__/agentInputProjection.test.ts
new file mode 100644
index 0000000000..b35ec433fa
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/agentInputProjection.test.ts
@@ -0,0 +1,166 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ AGENT_MESSAGE_REFERENCE_MAX_CHARS,
+ projectAgentFacingText,
+ projectPersistedAgentFacingUserText,
+ readAgentInputReferences,
+ type AgentInputReference,
+} from '../agentInputProjection.js';
+
+const QUOTE_MARKER = '> <!-- cindy-composer-quote -->';
+
+function rangeFor<T extends Omit<AgentInputReference, 'start' | 'end'>>(
+ text: string,
+ href: string,
+ reference: T,
+): T & { start: number; end: number } {
+ const start = text.indexOf(href);
+ if (start < 0) throw new Error(`missing href in fixture: ${href}`);
+ return { ...reference, start, end: start + href.length };
+}
+
+describe('agent-facing Composer projection', () => {
+ it('removes exact quote marker lines only when quotesEncoded is true without mutating input', () => {
+ const text = `${QUOTE_MARKER}\n> selected\n\nreply`;
+ const source = { text, quotesEncoded: true };
+
+ expect(projectAgentFacingText(source)).toBe('> selected\n\nreply');
+ expect(source).toEqual({ text, quotesEncoded: true });
+ expect(projectAgentFacingText({ text, quotesEncoded: false })).toBe(text);
+ expect(projectAgentFacingText({ text })).toBe(text);
+ });
+
+ it('projects message, conversation and project chips in source order', () => {
+ const messageHref = 'cindy://session/session-a?message=message-a';
+ const sessionHref = 'cindy://session/session-b';
+ const projectHref = 'cindy://project/%2Frepos%2Fcindy';
+ const text = `Read ${messageHref}, continue [Planning](${sessionHref}), then open ${projectHref}.`;
+ const message = rangeFor(text, messageHref, {
+ kind: 'message' as const,
+ href: messageHref,
+ sessionId: 'stale-session',
+ messageClientId: 'stale-message',
+ text: 'Full target message body',
+ });
+ const sessionStart = text.indexOf('[Planning]');
+ const sessionEnd = text.indexOf(')', sessionStart) + 1;
+ const references: AgentInputReference[] = [
+ message,
+ {
+ kind: 'session',
+ start: sessionStart,
+ end: sessionEnd,
+ href: sessionHref,
+ sessionId: 'stale-session',
+ title: 'Planning',
+ },
+ rangeFor(text, projectHref, {
+ kind: 'project' as const,
+ href: projectHref,
+ name: 'Cindy',
+ workingDir: '/stale/path',
+ }),
+ ];
+
+ const projected = projectAgentFacingText({ text, agentReferences: references });
+
+ expect(projected.indexOf('[Referenced message]'))
+ .toBeLessThan(projected.indexOf('[Referenced conversation]'));
+ expect(projected.indexOf('[Referenced conversation]'))
+ .toBeLessThan(projected.indexOf('[Referenced project]'));
+ expect(projected).toContain('Session ID: session-a');
+ expect(projected).toContain('Message ID: message-a');
+ expect(projected).toContain('Full target message body');
+ expect(projected).toContain('Title: Planning');
+ expect(projected).toContain('Session ID: session-b');
+ expect(projected).toContain('Name: Cindy');
+ expect(projected).toContain('Working directory: /repos/cindy');
+ expect(projected).not.toContain(messageHref);
+ expect(projected).not.toContain(sessionHref);
+ expect(projected).not.toContain(projectHref);
+ });
+
+ it('ignores stale spans and overlapping duplicate metadata', () => {
+ const href = 'cindy://session/session-a';
+ const text = `prefix ${href} suffix`;
+ const start = text.indexOf(href);
+ const valid: AgentInputReference = {
+ kind: 'session',
+ start,
+ end: start + href.length,
+ href,
+ sessionId: 'session-a',
+ title: 'Valid',
+ };
+ const stale: AgentInputReference = {
+ ...valid,
+ start: 0,
+ };
+ const duplicate: AgentInputReference = {
+ ...valid,
+ title: 'Duplicate',
+ };
+
+ expect(readAgentInputReferences([stale], text)).toEqual([]);
+ expect(readAgentInputReferences([valid, duplicate], text)).toEqual([valid]);
+ expect(projectAgentFacingText({ text, agentReferences: [stale] })).toBe(text);
+ });
+
+ it('bounds referenced message content and marks truncation explicitly', () => {
+ const href = 'cindy://session/session-a?message=message-a';
+ const body = 'x'.repeat(AGENT_MESSAGE_REFERENCE_MAX_CHARS + 10);
+ const reference = rangeFor(href, href, {
+ kind: 'message' as const,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: body,
+ });
+
+ const projected = projectAgentFacingText({ text: href, agentReferences: [reference] });
+
+ expect(projected).toContain('x'.repeat(AGENT_MESSAGE_REFERENCE_MAX_CHARS));
+ expect(projected).not.toContain('x'.repeat(AGENT_MESSAGE_REFERENCE_MAX_CHARS + 1));
+ expect(projected).toContain('[Content truncated]');
+ });
+
+ it('strips long trailing slash runs from untrusted session and project links', () => {
+ const slashes = '/'.repeat(50_000);
+ const messageHref = `cindy://session/session-a${slashes}?message=message-a`;
+ const projectHref = `cindy://project/%2Frepos%2Fcindy${slashes}`;
+ const text = `${messageHref} ${projectHref}`;
+ const references: AgentInputReference[] = [
+ rangeFor(text, messageHref, {
+ kind: 'message' as const,
+ href: messageHref,
+ sessionId: 'stale-session',
+ messageClientId: 'stale-message',
+ text: 'Target body',
+ }),
+ rangeFor(text, projectHref, {
+ kind: 'project' as const,
+ href: projectHref,
+ name: 'Cindy',
+ workingDir: '/stale/path',
+ }),
+ ];
+
+ const projected = projectAgentFacingText({ text, agentReferences: references });
+ expect(projected).toContain('Session ID: session-a');
+ expect(projected).toContain('Message ID: message-a');
+ expect(projected).toContain('Working directory: /repos/cindy');
+ });
+
+ it('projects persisted envelopes while preserving hand-written markers without the flag', () => {
+ const text = `${QUOTE_MARKER}\n> selected`;
+ expect(projectPersistedAgentFacingUserText(JSON.stringify({
+ text,
+ quotesEncoded: true,
+ }))).toBe('> selected');
+ expect(projectPersistedAgentFacingUserText({
+ text,
+ quotesEncoded: false,
+ })).toBe(text);
+ });
+});
diff --git a/packages/maker-shared/src/__tests__/messagePresentation.test.ts b/packages/maker-shared/src/__tests__/messagePresentation.test.ts
index 77a595116b..6d47e5aea0 100644
--- a/packages/maker-shared/src/__tests__/messagePresentation.test.ts
+++ b/packages/maker-shared/src/__tests__/messagePresentation.test.ts
@@ -82,8 +82,7 @@ describe('messagePresentation', () => {
expect(buildMessageActionBarPresentation({
align: 'agent',
canCopy: true,
- canFork: true,
- canRewind: true,
+ hasMoreActions: true,
hasTime: true,
hasTurnCost: true,
isStreaming: false,
@@ -91,15 +90,13 @@ describe('messagePresentation', () => {
align: 'left',
buttonSize: 24,
iconSize: 14,
- items: ['copy', 'fork', 'time', 'cost'],
+ items: ['copy', 'more', 'time', 'cost'],
});
expect(buildMessageActionBarPresentation({
align: 'user',
canCopy: true,
- canDelete: true,
- canFork: true,
- canRewind: true,
+ hasMoreActions: true,
hasTime: true,
hasTurnCost: true,
isStreaming: false,
@@ -107,14 +104,13 @@ describe('messagePresentation', () => {
align: 'right',
buttonSize: 24,
iconSize: 14,
- items: ['time', 'copy', 'rewind', 'fork', 'delete'],
+ items: ['time', 'copy', 'more'],
});
expect(buildMessageActionBarPresentation({
align: 'agent',
canCopy: true,
- canFork: true,
- canRewind: false,
+ hasMoreActions: true,
hasTime: true,
hasTurnCost: true,
isStreaming: true,
diff --git a/packages/maker-shared/src/agentInputProjection.ts b/packages/maker-shared/src/agentInputProjection.ts
new file mode 100644
index 0000000000..548f134a08
--- /dev/null
+++ b/packages/maker-shared/src/agentInputProjection.ts
@@ -0,0 +1,315 @@
+import { stripChatQuoteMarkerLines } from './chatQuotes.js';
+import { allDeepLinkSchemes } from './brandIdentity.js';
+
+/** Maximum copied target-message text kept in one Composer reference. */
+export const AGENT_MESSAGE_REFERENCE_MAX_CHARS = 12_000;
+
+/** Common source range for a structured Composer reference. */
+interface AgentInputReferenceBase {
+ /** Offsets in the persisted/wire `text`, before quote-marker projection. */
+ start: number;
+ end: number;
+ /** Cindy deep link retained only as stable location metadata. */
+ href: string;
+}
+
+/** One message-anchor chip and the readable target message it represents. */
+export interface AgentInputMessageReference extends AgentInputReferenceBase {
+ kind: 'message';
+ sessionId: string;
+ messageClientId: string;
+ /** Readable target body. Main may hydrate this before queue acceptance. */
+ text?: string;
+ truncated?: boolean;
+}
+
+/** One whole-session chip. It identifies a conversation; it does not imply transcript import. */
+export interface AgentInputSessionReference extends AgentInputReferenceBase {
+ kind: 'session';
+ sessionId: string;
+ title?: string;
+}
+
+/** One project chip with the decoded filesystem location. */
+export interface AgentInputProjectReference extends AgentInputReferenceBase {
+ kind: 'project';
+ name: string;
+ workingDir: string;
+}
+
+/** Structured Composer references preserved beside the human-facing wire text. */
+export type AgentInputReference =
+ | AgentInputMessageReference
+ | AgentInputSessionReference
+ | AgentInputProjectReference;
+
+/** Immutable inputs required to derive the text sent to semantic consumers. */
+export interface AgentFacingTextSource {
+ text: string;
+ quotesEncoded?: boolean;
+ agentReferences?: readonly AgentInputReference[];
+}
+
+/** Bounded readable message text plus an explicit truncation bit. */
+export interface BoundedAgentReferenceText {
+ text: string;
+ truncated: boolean;
+}
+
+/** Keep message-reference payloads bounded without using the compact UI label. */
+export function boundAgentReferenceText(
+ value: string,
+ cap = AGENT_MESSAGE_REFERENCE_MAX_CHARS,
+): BoundedAgentReferenceText {
+ const text = value.trim();
+ if (text.length <= cap) return { text, truncated: false };
+ return { text: text.slice(0, cap), truncated: true };
+}
+
+function nonEmptyString(value: unknown): value is string {
+ return typeof value === 'string' && value.length > 0;
+}
+
+function stripDeepLinkPrefix(href: string, route: 'session/' | 'project/'): string | null {
+ for (const scheme of allDeepLinkSchemes()) {
+ const prefix = `${scheme}://${route}`;
+ if (href.startsWith(prefix)) return href.slice(prefix.length);
+ }
+ return null;
+}
+
+/** Remove a trailing slash run in one linear pass over untrusted deep-link input. */
+function stripTrailingSlashes(value: string): string {
+ let end = value.length;
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
+ return end === value.length ? value : value.slice(0, end);
+}
+
+function parseSessionHref(
+ href: string,
+): { sessionId: string; messageClientId: string | null } | null {
+ const rest = stripDeepLinkPrefix(href, 'session/');
+ if (rest === null) return null;
+ const hashIndex = rest.indexOf('#');
+ const withoutHash = hashIndex >= 0 ? rest.slice(0, hashIndex) : rest;
+ const queryIndex = withoutHash.indexOf('?');
+ const rawSessionId = stripTrailingSlashes(
+ queryIndex >= 0 ? withoutHash.slice(0, queryIndex) : withoutHash
+ );
+ if (!rawSessionId) return null;
+ let sessionId: string;
+ try {
+ sessionId = decodeURIComponent(rawSessionId);
+ } catch {
+ return null;
+ }
+ if (!sessionId) return null;
+ let messageClientId: string | null = null;
+ if (queryIndex >= 0) {
+ const query = withoutHash.slice(queryIndex + 1);
+ for (const pair of query.split('&')) {
+ const equalsIndex = pair.indexOf('=');
+ if (equalsIndex <= 0 || pair.slice(0, equalsIndex) !== 'message') continue;
+ const rawMessageClientId = pair.slice(equalsIndex + 1);
+ if (!rawMessageClientId) break;
+ try {
+ messageClientId = decodeURIComponent(rawMessageClientId) || null;
+ } catch {
+ messageClientId = null;
+ }
+ break;
+ }
+ }
+ return { sessionId, messageClientId };
+}
+
+function parseProjectHref(href: string): { workingDir: string } | null {
+ const rest = stripDeepLinkPrefix(href, 'project/');
+ if (rest === null) return null;
+ const hashIndex = rest.indexOf('#');
+ const withoutHash = hashIndex >= 0 ? rest.slice(0, hashIndex) : rest;
+ const queryIndex = withoutHash.indexOf('?');
+ const rawWorkingDir = stripTrailingSlashes(
+ queryIndex >= 0 ? withoutHash.slice(0, queryIndex) : withoutHash
+ );
+ if (!rawWorkingDir) return null;
+ try {
+ const workingDir = decodeURIComponent(rawWorkingDir);
+ return workingDir ? { workingDir } : null;
+ } catch {
+ return null;
+ }
+}
+
+function referenceSpanMatchesHref(span: string, href: string): boolean {
+ return span === href || (
+ span.startsWith('[')
+ && span.endsWith(`](${href})`)
+ );
+}
+
+function readReference(
+ value: unknown,
+ sourceText: string,
+): AgentInputReference | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const candidate = value as Record<string, unknown>;
+ if (
+ !Number.isSafeInteger(candidate.start)
+ || !Number.isSafeInteger(candidate.end)
+ || !nonEmptyString(candidate.href)
+ ) return null;
+ const start = candidate.start as number;
+ const end = candidate.end as number;
+ if (start < 0 || end <= start || end > sourceText.length) return null;
+ // The metadata must still point at the exact persisted deep-link span. This
+ // rejects stale offsets after arbitrary queue edits instead of replacing
+ // unrelated user text with a semantic block.
+ if (!referenceSpanMatchesHref(sourceText.slice(start, end), candidate.href)) return null;
+
+ if (candidate.kind === 'message') {
+ const target = parseSessionHref(candidate.href);
+ if (!target?.messageClientId) return null;
+ return {
+ kind: 'message',
+ start,
+ end,
+ href: candidate.href,
+ sessionId: target.sessionId,
+ messageClientId: target.messageClientId,
+ ...(typeof candidate.text === 'string' ? { text: candidate.text } : {}),
+ ...(candidate.truncated === true ? { truncated: true } : {}),
+ };
+ }
+ if (candidate.kind === 'session') {
+ const target = parseSessionHref(candidate.href);
+ if (!target || target.messageClientId) return null;
+ return {
+ kind: 'session',
+ start,
+ end,
+ href: candidate.href,
+ sessionId: target.sessionId,
+ ...(nonEmptyString(candidate.title) ? { title: candidate.title } : {}),
+ };
+ }
+ if (candidate.kind === 'project' && nonEmptyString(candidate.name)) {
+ const target = parseProjectHref(candidate.href);
+ if (!target) return null;
+ return {
+ kind: 'project',
+ start,
+ end,
+ href: candidate.href,
+ name: candidate.name,
+ workingDir: target.workingDir,
+ };
+ }
+ return null;
+}
+
+/** Validate untrusted persisted/remote reference metadata against its wire text. */
+export function readAgentInputReferences(
+ value: unknown,
+ sourceText: string,
+): AgentInputReference[] {
+ if (!Array.isArray(value)) return [];
+ const references = value
+ .map((candidate) => readReference(candidate, sourceText))
+ .filter((candidate): candidate is AgentInputReference => candidate !== null)
+ .sort((left, right) => left.start - right.start || left.end - right.end);
+ const nonOverlapping: AgentInputReference[] = [];
+ let previousEnd = 0;
+ for (const reference of references) {
+ if (reference.start < previousEnd) continue;
+ nonOverlapping.push(reference);
+ previousEnd = reference.end;
+ }
+ return nonOverlapping;
+}
+
+function oneLine(value: string): string {
+ return value.replace(/\s+/g, ' ').trim();
+}
+
+function formatReference(reference: AgentInputReference): string {
+ if (reference.kind === 'message') {
+ const bounded = boundAgentReferenceText(reference.text ?? '');
+ const truncated = reference.truncated === true || bounded.truncated;
+ return [
+ '[Referenced message]',
+ `Session ID: ${reference.sessionId}`,
+ `Message ID: ${reference.messageClientId}`,
+ 'Content:',
+ bounded.text || '(message content unavailable)',
+ ...(truncated ? ['[Content truncated]'] : []),
+ '[/Referenced message]',
+ ].join('\n');
+ }
+ if (reference.kind === 'session') {
+ return [
+ '[Referenced conversation]',
+ `Title: ${oneLine(reference.title ?? '') || `Conversation ${reference.sessionId}`}`,
+ `Session ID: ${reference.sessionId}`,
+ '[/Referenced conversation]',
+ ].join('\n');
+ }
+ return [
+ '[Referenced project]',
+ `Name: ${oneLine(reference.name)}`,
+ `Working directory: ${reference.workingDir}`,
+ '[/Referenced project]',
+ ].join('\n');
+}
+
+function projectLiteralText(text: string, quotesEncoded: boolean): string {
+ return quotesEncoded ? stripChatQuoteMarkerLines(text) : text;
+}
+
+/**
+ * Derive immutable agent-facing text from Composer wire data.
+ *
+ * The persisted text remains untouched. Quote markers are removed only when
+ * their persisted flag is true, while structured reference spans are replaced
+ * in source order with readable semantic blocks.
+ */
+export function projectAgentFacingText(source: AgentFacingTextSource): string {
+ const references = readAgentInputReferences(source.agentReferences, source.text);
+ const stripMarkers = source.quotesEncoded === true;
+ if (references.length === 0) return projectLiteralText(source.text, stripMarkers);
+
+ const parts: string[] = [];
+ let cursor = 0;
+ for (const reference of references) {
+ parts.push(projectLiteralText(source.text.slice(cursor, reference.start), stripMarkers));
+ parts.push(formatReference(reference));
+ cursor = reference.end;
+ }
+ parts.push(projectLiteralText(source.text.slice(cursor), stripMarkers));
+ return parts.join('');
+}
+
+/**
+ * Project the persisted `{text, quotesEncoded, agentReferences}` envelope.
+ * Returns null for non-user/unknown shapes so callers can keep their existing
+ * assistant/tool extraction logic.
+ */
+export function projectPersistedAgentFacingUserText(content: unknown): string | null {
+ let value = content;
+ if (typeof value === 'string') {
+ if (!value || (value[0] !== '{' && value[0] !== '[')) return null;
+ try {
+ value = JSON.parse(value);
+ } catch {
+ return null;
+ }
+ }
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const record = value as Record<string, unknown>;
+ if (typeof record.text !== 'string') return null;
+ return projectAgentFacingText({
+ text: record.text,
+ quotesEncoded: record.quotesEncoded === true,
+ agentReferences: readAgentInputReferences(record.agentReferences, record.text),
+ });
+}
diff --git a/packages/maker-shared/src/index.ts b/packages/maker-shared/src/index.ts
index 01dea5c600..6ca5712476 100644
--- a/packages/maker-shared/src/index.ts
+++ b/packages/maker-shared/src/index.ts
@@ -1,4 +1,5 @@
export * from './agentCapabilities.js';
+export * from './agentInputProjection.js';
export * from './agentTask.js';
export * from './branding.js';
export * from './brandIdentity.js';
diff --git a/packages/maker-shared/src/messagePresentation.ts b/packages/maker-shared/src/messagePresentation.ts
index 7091e52072..f64a850194 100644
--- a/packages/maker-shared/src/messagePresentation.ts
+++ b/packages/maker-shared/src/messagePresentation.ts
@@ -84,14 +84,12 @@ export interface TodoCardPresentation {
export type MessageActionBarAlignment = 'left' | 'right';
-export type MessageActionBarItemId = 'copy' | 'cost' | 'delete' | 'fork' | 'rewind' | 'streaming' | 'time';
+export type MessageActionBarItemId = 'copy' | 'cost' | 'more' | 'streaming' | 'time';
export interface MessageActionBarPresentationInput {
align: 'agent' | 'user';
canCopy: boolean;
- canDelete?: boolean;
- canFork: boolean;
- canRewind: boolean;
+ hasMoreActions?: boolean;
hasTime: boolean;
hasTurnCost: boolean;
isStreaming: boolean;
@@ -339,17 +337,14 @@ export function buildMessageActionBarPresentation(
const agentItems: Array<MessageActionBarItemId | null> = [
input.canCopy ? 'copy' : null,
- input.canFork ? 'fork' : null,
- input.canDelete ? 'delete' : null,
+ input.hasMoreActions ? 'more' : null,
input.hasTime ? 'time' : null,
input.hasTurnCost ? 'cost' : null,
];
const userItems: Array<MessageActionBarItemId | null> = [
input.hasTime ? 'time' : null,
input.canCopy ? 'copy' : null,
- input.canRewind ? 'rewind' : null,
- input.canFork ? 'fork' : null,
- input.canDelete ? 'delete' : null,
+ input.hasMoreActions ? 'more' : null,
];
const items = (input.align === 'agent' ? agentItems : userItems).filter(isMessageActionBarItemId);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5abd8590d9..f31c8d45c4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -27,6 +27,9 @@ patchedDependencies:
hash: 4f76ca2497d14d136ef6ff35060f4c35b57319a3edf53fa334b82771a9405c16
path: dependency-patches/[email protected]
+ hash: 9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d
+ path: dependency-patches/[email protected]
importers:
@@ -513,43 +516,46 @@ importers:
version: link:../../packages/voice-input-core
'@expo/metro-runtime':
specifier: ^56.0.15
+ version: 56.0.17(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
'@legendapp/list':
specifier: ^3.3.3
+ version: 3.3.3([email protected]([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
'@noble/hashes':
specifier: ^1.8.0
version: 1.8.0
'@react-native-async-storage/async-storage':
specifier: 2.2.0
+ version: 2.2.0([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
'@react-native-google-signin/google-signin':
specifier: 16.1.2
+ version: 16.1.2([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
'@types/pako':
specifier: ^2.0.4
version: 2.0.4
expo:
specifier: ~56.0.12
+ version: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
expo-apple-authentication:
specifier: ~56.0.4
+ version: 56.0.4([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-audio:
specifier: ^56.0.12
+ version: 56.0.12([email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-auth-session:
specifier: ^56.0.14
+ version: 56.0.15([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-blur:
specifier: ~56.0.3
+ version: 56.0.4([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ expo-build-properties:
+ specifier: ~56.0.23
+ version: 56.0.23([email protected])
expo-clipboard:
specifier: ^56.0.4
+ version: 56.0.4([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-constants:
specifier: ^56.0.18
+ version: 56.0.21([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
expo-crypto:
specifier: ^56.0.4
version: 56.0.4([email protected])
@@ -558,16 +564,16 @@ importers:
version: 56.0.4([email protected])
expo-file-system:
specifier: ^56.0.8
+ version: 56.0.8([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
expo-font:
specifier: ~56.0.7
+ version: 56.0.7([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-glass-effect:
specifier: ~56.0.4
+ version: 56.0.4([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-image:
specifier: ~56.0.11
+ version: 56.0.11([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-image-manipulator:
specifier: ~56.0.20
version: 56.0.22([email protected])
@@ -576,46 +582,46 @@ importers:
version: 56.0.21([email protected])
expo-linking:
specifier: ^56.0.14
+ version: 56.0.15([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-localization:
specifier: ~56.0.6
expo-media-library:
specifier: ~56.0.8
+ version: 56.0.9([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
expo-notifications:
specifier: ~56.0.22
+ version: 56.0.22([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected])
expo-observe:
specifier: ~56.0.21
+ version: 56.0.25([email protected])([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-paste-input:
specifier: 0.2.2
- version: 0.2.2(patch_hash=53be555646735a171c1624f074ef30e5ca897a7b8893724bc2d0d51682f769d8)([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ version: 0.2.2(patch_hash=53be555646735a171c1624f074ef30e5ca897a7b8893724bc2d0d51682f769d8)([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-router:
specifier: ^56.2.11
- version: 56.2.15(6044494e4d6bcce799344359eb657455)
+ version: 56.2.15(600de089274a49ab6ec9549ee6c8284a)
expo-secure-store:
specifier: ^56.0.4
version: 56.0.4([email protected])
expo-sharing:
specifier: ~56.0.18
+ version: 56.0.22([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected])
expo-splash-screen:
specifier: ~56.0.13
expo-status-bar:
specifier: ~56.0.4
+ version: 56.0.4([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-updates:
specifier: ~56.0.19
+ version: 56.0.22([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-web-browser:
specifier: ^56.0.5
+ version: 56.0.5([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
lucide-react-native:
specifier: 0.468.0
+ version: 0.468.0([email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
pako:
specifier: ^2.1.0
version: 2.2.0
@@ -627,46 +633,46 @@ importers:
version: 19.2.3([email protected])
react-native:
specifier: 0.85.3
- version: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ version: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
react-native-gesture-handler:
specifier: 3.0.2
+ version: 3.0.2([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
react-native-reanimated:
specifier: 4.3.1
+ version: 4.3.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
react-native-safe-area-context:
specifier: ~5.7.0
+ version: 5.7.0([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
react-native-screens:
specifier: ~4.25.2
+ version: 4.25.2([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
react-native-svg:
specifier: 15.15.4
+ version: 15.15.4([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
react-native-uitextview:
specifier: 2.2.0
- version: 2.2.0(patch_hash=d6eb1ea155bf2245746f79c5d2cc7c5abe165c34e55c464e04d641a78888cda0)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ version: 2.2.0(patch_hash=d6eb1ea155bf2245746f79c5d2cc7c5abe165c34e55c464e04d641a78888cda0)([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
react-native-web:
specifier: ^0.21.2
react-native-webview:
specifier: 13.16.1
- version: 13.16.1(patch_hash=4f76ca2497d14d136ef6ff35060f4c35b57319a3edf53fa334b82771a9405c16)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ version: 13.16.1(patch_hash=4f76ca2497d14d136ef6ff35060f4c35b57319a3edf53fa334b82771a9405c16)([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
react-native-worklets:
specifier: 0.8.3
+ version: 0.8.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
xdt-ios-app-distribution:
specifier: file:./modules/xdt-ios-app-distribution
+ version: file:apps/mobile/modules/xdt-ios-app-distribution([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected])
xdt-mobile-realtime-audio:
specifier: file:./modules/xdt-mobile-realtime-audio
version: file:apps/mobile/modules/xdt-mobile-realtime-audio
xdt-tapdb:
specifier: file:./modules/xdt-tapdb
+ version: file:apps/mobile/modules/xdt-tapdb([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected])
xdt-wechat-login:
specifier: file:./modules/xdt-wechat-login
+ version: file:apps/mobile/modules/xdt-wechat-login([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected])
devDependencies:
'@types/react':
specifier: ~19.2.0
@@ -6541,6 +6547,11 @@ packages:
react: '*'
react-native: '*'
+ resolution: {integrity: sha512-xb9QX+x/AsDw8wVdox3jNpf8eVUc8PYq3lycF2OOlmHkmn+ecmxmtdCpB3ZDLjtdem8XrgycgLIba7WTdc7o7w==}
+ peerDependencies:
+ expo: '*'
+
resolution: {integrity: sha512-qb4DYlkiowHYHaUYVT2FN9nk/nI1xShXOUYsI7J9dVpQCOHcGFjCBPX1VAvEW4Ye4/Aagd6IuhOVAq/+scBOiA==}
peerDependencies:
@@ -12162,7 +12173,7 @@ snapshots:
'@expo-google-fonts/[email protected]': {}
dependencies:
'@expo/code-signing-certificates': 0.0.6
'@expo/config': 56.0.12([email protected])
@@ -12172,7 +12183,7 @@ snapshots:
'@expo/image-utils': 0.10.3([email protected])
'@expo/inline-modules': 0.0.14([email protected])
'@expo/json-file': 10.2.0
+ '@expo/log-box': 56.0.14(@expo/[email protected])([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
'@expo/metro': 56.0.0
'@expo/metro-config': 56.0.17([email protected])([email protected])
'@expo/metro-file-map': 56.0.3
@@ -12198,7 +12209,7 @@ snapshots:
connect: 3.7.0
debug: 4.4.3
dnssd-advertise: 1.1.6
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
expo-server: 56.0.5
fetch-nodeshim: 0.4.10
getenv: 2.0.0
@@ -12224,8 +12235,8 @@ snapshots:
ws: 8.21.1
zod: 4.3.6
optionalDependencies:
- expo-router: 56.2.15(6044494e4d6bcce799344359eb657455)
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ expo-router: 56.2.15(600de089274a49ab6ec9549ee6c8284a)
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- '@expo/dom-webview'
- '@expo/metro-runtime'
@@ -12287,18 +12298,18 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@expo/[email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])':
dependencies:
chalk: 4.1.2
optionalDependencies:
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ '@expo/[email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])':
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
@@ -12385,13 +12396,13 @@ snapshots:
- supports-color
- typescript
+ '@expo/[email protected](@expo/[email protected])([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])':
dependencies:
+ '@expo/dom-webview': 56.0.6([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
anser: 1.4.10
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
stacktrace-parser: 0.1.11
@@ -12420,7 +12431,7 @@ snapshots:
postcss: 8.5.19
resolve-from: 5.0.0
optionalDependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
transitivePeerDependencies:
- bufferutil
- supports-color
@@ -12438,14 +12449,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@expo/[email protected](@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])':
dependencies:
+ '@expo/log-box': 56.0.14(@expo/[email protected])([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
anser: 1.4.10
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
pretty-format: 29.7.0
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
stacktrace-parser: 0.1.11
whatwg-fetch: 3.6.20
optionalDependencies:
@@ -12530,14 +12541,14 @@ snapshots:
dependencies:
debug: 4.4.3
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ expo-constants: 56.0.21([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
+ expo-font: 56.0.7([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-server: 56.0.5
react: 19.2.3
optionalDependencies:
- expo-router: 56.2.15(6044494e4d6bcce799344359eb657455)
+ '@expo/metro-runtime': 56.0.17(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ expo-router: 56.2.15(600de089274a49ab6ec9549ee6c8284a)
react-dom: 19.2.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -12552,17 +12563,17 @@ snapshots:
'@expo/[email protected]': {}
+ '@expo/[email protected](@babel/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])':
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
sf-symbols-typescript: 2.2.0
optionalDependencies:
'@babel/core': 7.29.7
react-dom: 19.2.3([email protected])
+ react-native-worklets: 0.8.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
transitivePeerDependencies:
- '@types/react'
- '@types/react-dom'
@@ -13014,13 +13025,13 @@ snapshots:
- supports-color
- utf-8-validate
+ '@legendapp/[email protected]([email protected]([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])':
dependencies:
react: 19.2.3
use-sync-external-store: 1.6.0([email protected])
optionalDependencies:
react-dom: 19.2.3([email protected])
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
'@lezer/[email protected]': {}
@@ -13800,22 +13811,22 @@ snapshots:
'@radix-ui/[email protected]': {}
+ '@react-native-async-storage/[email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))':
dependencies:
merge-options: 3.0.4
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ '@react-native-google-signin/[email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])':
dependencies:
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
optionalDependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ '@react-native-masked-view/[email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])':
dependencies:
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
'@react-native/[email protected]': {}
@@ -13947,12 +13958,12 @@ snapshots:
'@react-native/[email protected]': {}
+ '@react-native/[email protected](@types/[email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])':
dependencies:
invariant: 2.2.4
nullthrows: 1.1.1
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
optionalDependencies:
'@types/react': 19.2.17
@@ -15173,7 +15184,7 @@ snapshots:
react-refresh: 0.14.2
optionalDependencies:
'@babel/runtime': 7.29.7
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
transitivePeerDependencies:
- '@babel/core'
- supports-color
@@ -16621,130 +16632,137 @@ snapshots:
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
expo-updates-interface: 56.0.2([email protected])
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected]):
dependencies:
'@expo/image-utils': 0.10.3([email protected])
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ expo-constants: 56.0.21([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
- typescript
+ [email protected]([email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected]))([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ expo-asset: 56.0.20([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected])
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
expo-application: 56.0.3([email protected])
+ expo-constants: 56.0.21([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
expo-crypto: 56.0.4([email protected])
+ expo-linking: 56.0.15([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ expo-web-browser: 56.0.5([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
invariant: 2.2.4
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- expo
- supports-color
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+
+ dependencies:
+ '@expo/schema-utils': 56.0.2
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ resolve-from: 5.0.0
+ semver: 7.8.5
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])):
dependencies:
'@expo/env': 2.3.1
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])):
dependencies:
'@expo/env': 2.3.1
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])):
dependencies:
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
fontfaceobserver: 2.3.0
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
expo-image-loader: 56.0.3([email protected])
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
expo-image-loader: 56.0.3([email protected])
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
sf-symbols-typescript: 2.2.0
optionalDependencies:
@@ -16753,34 +16771,34 @@ snapshots:
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo-constants: 56.0.21([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
invariant: 2.2.4
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- expo
- supports-color
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
rtl-detect: 1.1.2
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
expo-json-utils: 56.0.0
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])):
dependencies:
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
@@ -16792,71 +16810,71 @@ snapshots:
- supports-color
- typescript
+ [email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
'@expo/expo-modules-macros-plugin': 0.2.2
- expo-modules-jsi: 56.0.12([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
+ expo-modules-jsi: 56.0.12([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
invariant: 2.2.4
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
optionalDependencies:
+ react-native-worklets: 0.8.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ [email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])):
dependencies:
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected]):
dependencies:
'@expo/image-utils': 0.10.4([email protected])
abort-controller: 3.0.0
badgin: 1.2.3
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
expo-application: 56.0.3([email protected])
+ expo-constants: 56.0.22([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
- typescript
+ [email protected]([email protected])([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ expo-app-metrics: 56.0.22([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-eas-client: 56.0.1
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
optionalDependencies:
- expo-router: 56.2.15(6044494e4d6bcce799344359eb657455)
+ expo-router: 56.2.15(600de089274a49ab6ec9549ee6c8284a)
- [email protected](patch_hash=53be555646735a171c1624f074ef30e5ca897a7b8893724bc2d0d51682f769d8)([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
+ [email protected](patch_hash=53be555646735a171c1624f074ef30e5ca897a7b8893724bc2d0d51682f769d8)([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
- [email protected](6044494e4d6bcce799344359eb657455):
+ [email protected](600de089274a49ab6ec9549ee6c8284a):
dependencies:
+ '@expo/log-box': 56.0.14(@expo/[email protected])([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ '@expo/metro-runtime': 56.0.17(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
'@expo/schema-utils': 56.0.2
+ '@expo/ui': 56.0.22(@babel/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
'@radix-ui/react-slot': 1.3.0(@types/[email protected])([email protected])
- '@react-native-masked-view/masked-view': 0.3.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ '@react-native-masked-view/masked-view': 0.3.2([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
'@testing-library/jest-dom': 6.9.1
'@testing-library/user-event': 14.6.1(@testing-library/[email protected])
client-only: 0.0.1
color: 4.2.3
debug: 4.4.3
escape-string-regexp: 4.0.0
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ expo-constants: 56.0.21([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
+ expo-glass-effect: 56.0.4([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ expo-linking: 56.0.15([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-server: 56.0.5
+ expo-symbols: 56.0.6([email protected])([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
fast-deep-equal: 3.1.3
invariant: 2.2.4
nanoid: 3.3.16
@@ -16864,10 +16882,10 @@ snapshots:
react: 19.2.3
react-fast-compare: 3.2.2
react-is: 19.2.7
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
- react-native-safe-area-context: 5.7.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native-drawer-layout: 4.2.7(21b723e89fd1804f167839b48ef1ed52)
+ react-native-safe-area-context: 5.7.0([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native-screens: 4.25.2([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
server-only: 0.0.1
sf-symbols-typescript: 2.2.0
shallowequal: 1.1.0
@@ -16875,8 +16893,8 @@ snapshots:
optionalDependencies:
react-dom: 19.2.3([email protected])
- react-native-gesture-handler: 3.0.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native-gesture-handler: 3.0.2([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native-reanimated: 4.3.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
transitivePeerDependencies:
- '@babel/core'
@@ -16889,18 +16907,18 @@ snapshots:
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected]):
dependencies:
'@expo/config-plugins': 56.0.13([email protected])
'@expo/config-types': 56.0.7
'@expo/plist': 0.7.0
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
- typescript
@@ -16909,34 +16927,34 @@ snapshots:
dependencies:
'@expo/config-plugins': 56.0.13([email protected])
'@expo/image-utils': 0.10.3([email protected])
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
xml2js: 0.6.0
transitivePeerDependencies:
- supports-color
- typescript
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected]([email protected])([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
'@expo-google-fonts/material-symbols': 0.4.40
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ expo-font: 56.0.7([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
sf-symbols-typescript: 2.2.0
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
'@expo/code-signing-certificates': 0.0.6
'@expo/plist': 0.7.0
@@ -16944,7 +16962,7 @@ snapshots:
arg: 4.1.3
chalk: 4.1.2
debug: 4.4.3
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
expo-eas-client: 56.0.1
expo-manifests: 56.0.4([email protected])
expo-structured-headers: 56.0.0
@@ -16954,48 +16972,48 @@ snapshots:
ignore: 5.3.2
nullthrows: 1.1.1
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
resolve-from: 5.0.0
transitivePeerDependencies:
- supports-color
+ [email protected]([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])):
dependencies:
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected](bedb3dfb85b4bb5081482612eab0a2c6):
dependencies:
'@babel/runtime': 7.29.7
'@expo/config': 56.0.12([email protected])
'@expo/config-plugins': 56.0.13([email protected])
+ '@expo/devtools': 56.0.2([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
'@expo/fingerprint': 0.19.8
'@expo/local-build-cache-provider': 56.0.10([email protected])
+ '@expo/log-box': 56.0.14(@expo/[email protected])([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
'@expo/metro': 56.0.0
'@expo/metro-config': 56.0.17([email protected])([email protected])
'@ungap/structured-clone': 1.3.3
babel-preset-expo: 56.0.17(@babel/[email protected])(@babel/[email protected])([email protected])([email protected])
+ expo-asset: 56.0.20([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected])
+ expo-constants: 56.0.21([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
+ expo-file-system: 56.0.8([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))
+ expo-font: 56.0.7([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
expo-keep-awake: 56.0.3([email protected])([email protected])
expo-modules-autolinking: 56.0.20([email protected])
+ expo-modules-core: 56.0.21([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
pretty-format: 29.7.0
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
react-refresh: 0.14.2
whatwg-url-minimum: 0.1.2
optionalDependencies:
+ '@expo/dom-webview': 56.0.6([email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ '@expo/metro-runtime': 56.0.17(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
react-dom: 19.2.3([email protected])
- react-native-webview: 13.16.1(patch_hash=4f76ca2497d14d136ef6ff35060f4c35b57319a3edf53fa334b82771a9405c16)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native-webview: 13.16.1(patch_hash=4f76ca2497d14d136ef6ff35060f4c35b57319a3edf53fa334b82771a9405c16)([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
transitivePeerDependencies:
- '@babel/core'
- bufferutil
@@ -18281,11 +18299,11 @@ snapshots:
dependencies:
yallist: 4.0.0
+ [email protected]([email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native-svg: 15.15.4([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
dependencies:
@@ -19672,59 +19690,59 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ [email protected](21b723e89fd1804f167839b48ef1ed52):
dependencies:
color: 4.2.3
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
- react-native-gesture-handler: 3.0.2([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native-gesture-handler: 3.0.2([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native-reanimated: 4.3.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
use-latest-callback: 0.2.6([email protected])
+ [email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
'@types/react-test-renderer': 19.1.0
invariant: 2.2.4
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
- react-native-is-edge-to-edge: 1.3.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native-is-edge-to-edge: 1.3.1([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ react-native-worklets: 0.8.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
semver: 7.8.5
+ [email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
react: 19.2.3
react-freeze: 1.0.4([email protected])
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
warn-once: 0.1.1
+ [email protected]([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
css-select: 5.2.2
css-tree: 1.1.3
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
warn-once: 0.1.1
- [email protected](patch_hash=d6eb1ea155bf2245746f79c5d2cc7c5abe165c34e55c464e04d641a78888cda0)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
+ [email protected](patch_hash=d6eb1ea155bf2245746f79c5d2cc7c5abe165c34e55c464e04d641a78888cda0)([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
dependencies:
@@ -19741,14 +19759,14 @@ snapshots:
transitivePeerDependencies:
- encoding
- [email protected](patch_hash=4f76ca2497d14d136ef6ff35060f4c35b57319a3edf53fa334b82771a9405c16)([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
+ [email protected](patch_hash=4f76ca2497d14d136ef6ff35060f4c35b57319a3edf53fa334b82771a9405c16)([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
escape-string-regexp: 4.0.0
invariant: 2.2.4
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ [email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]):
dependencies:
'@babel/core': 7.29.7
'@babel/plugin-transform-arrow-functions': 7.29.7(@babel/[email protected])
@@ -19763,12 +19781,12 @@ snapshots:
'@react-native/metro-config': 0.85.3(@babel/[email protected])
convert-source-map: 2.0.0
react: 19.2.3
- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ react-native: 0.85.3(patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
semver: 7.8.5
transitivePeerDependencies:
- supports-color
+ [email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]):
dependencies:
'@react-native/assets-registry': 0.85.3
'@react-native/codegen': 0.85.3(@babel/[email protected])
@@ -19776,7 +19794,7 @@ snapshots:
'@react-native/gradle-plugin': 0.85.3
'@react-native/js-polyfills': 0.85.3
'@react-native/normalize-colors': 0.85.3
- '@react-native/virtualized-lists': 0.85.3(@types/[email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ '@react-native/virtualized-lists': 0.85.3(@types/[email protected])([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
abort-controller: 3.0.0
anser: 1.4.10
ansi-regex: 5.0.1
@@ -21328,22 +21346,22 @@ snapshots:
simple-plist: 1.3.1
uuid: 7.0.3
+ xdt-ios-app-distribution@file:apps/mobile/modules/xdt-ios-app-distribution([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ expo-modules-core: 56.0.21([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
xdt-mobile-realtime-audio@file:apps/mobile/modules/xdt-mobile-realtime-audio: {}
+ xdt-tapdb@file:apps/mobile/modules/xdt-tapdb([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ expo-modules-core: 56.0.21([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ xdt-wechat-login@file:apps/mobile/modules/xdt-wechat-login([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected]):
dependencies:
+ expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
+ expo-modules-core: 56.0.21([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])