Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix: 上游 SSE 中断立即失败并保留会话终态 (#1062)

yan9e08f02867ee
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/remoteHistory.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/remoteHistory.test.ts
index 546af1b4b2..e0031dbbc8 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/remoteHistory.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/remoteHistory.test.ts
@@ -11,7 +11,14 @@ vi.mock('electron', () => ({
},
}));
-import { registerRemoteHistoryIpc } from '../history';
+import { registerRemoteHistoryIpc, type RemoteHistoryIpcDeps } from '../history';
+
+/** Tests default to "no terminal tail"; individual cases override readTerminal. */
+function register(
+ deps: Omit<RemoteHistoryIpcDeps, 'readTerminal'> & Partial<Pick<RemoteHistoryIpcDeps, 'readTerminal'>>,
+): void {
+ registerRemoteHistoryIpc({ readTerminal: async () => undefined, ...deps });
+}
const request = {
sessionId: 'session-1',
@@ -38,7 +45,7 @@ describe('local-db:history:messages', () => {
nextCursor: { createdAt: 800, id: 'message-8' },
hasMore: true,
}));
- registerRemoteHistoryIpc({
+ register({
sessionExists: vi.fn(async () => true),
getMessages,
});
@@ -63,7 +70,7 @@ describe('local-db:history:messages', () => {
it('distinguishes an existing empty session from a missing session', async () => {
const getMessages = vi.fn();
- registerRemoteHistoryIpc({
+ register({
sessionExists: vi.fn(async () => false),
getMessages,
});
@@ -75,7 +82,7 @@ describe('local-db:history:messages', () => {
it('rejects malformed cursors and out-of-range limits before reading', async () => {
const getMessages = vi.fn();
- registerRemoteHistoryIpc({
+ register({
sessionExists: vi.fn(async () => true),
getMessages,
});
@@ -94,7 +101,7 @@ describe('local-db:history:messages', () => {
});
it('caps source content only when a session-reference caller requests it', async () => {
- registerRemoteHistoryIpc({
+ register({
sessionExists: vi.fn(async () => true),
getMessages: vi.fn(async () => ({
items: [{
@@ -125,7 +132,7 @@ describe('local-db:history:messages', () => {
});
it('strips structured content envelopes before relaying capped rows', async () => {
- registerRemoteHistoryIpc({
+ register({
sessionExists: vi.fn(async () => true),
getMessages: vi.fn(async () => ({
items: [{
@@ -156,7 +163,7 @@ describe('local-db:history:messages', () => {
});
it('does not mark plain persisted text envelopes as truncated', async () => {
- registerRemoteHistoryIpc({
+ register({
sessionExists: vi.fn(async () => true),
getMessages: vi.fn(async () => ({
items: [{
@@ -188,7 +195,7 @@ describe('local-db:history:messages', () => {
});
it('caps plain rows while preserving structured rows in mixed-role reads', async () => {
- registerRemoteHistoryIpc({
+ register({
sessionExists: vi.fn(async () => true),
getMessages: vi.fn(async () => ({
items: [{
@@ -240,7 +247,7 @@ describe('local-db:history:messages', () => {
});
it('marks omitted reference metadata as truncated after flattening an envelope', async () => {
- registerRemoteHistoryIpc({
+ register({
sessionExists: vi.fn(async () => true),
getMessages: vi.fn(async () => ({
items: [{
@@ -276,7 +283,7 @@ describe('local-db:history:messages', () => {
});
it('drops non-text blocks when compacting structured history arrays', async () => {
- registerRemoteHistoryIpc({
+ register({
sessionExists: vi.fn(async () => true),
getMessages: vi.fn(async () => ({
items: [{
@@ -312,7 +319,7 @@ describe('local-db:history:messages', () => {
it('forwards a stable rowid history cursor', async () => {
const getMessages = vi.fn(async () => ({ items: [], nextCursor: null, hasMore: false }));
- registerRemoteHistoryIpc({
+ register({
sessionExists: vi.fn(async () => true),
getMessages,
});
@@ -325,4 +332,35 @@ describe('local-db:history:messages', () => {
cursor: { createdAt: 700, id: 'message-7', rowid: 42 },
}));
});
+
+ it('attaches the safe terminal marker computed in the same handler call', async () => {
+ const readTerminal = vi.fn(async () => ({ status: 'error' as const, createdAt: 500 }));
+ register({
+ sessionExists: vi.fn(async () => true),
+ getMessages: vi.fn(async () => ({ items: [], nextCursor: null, hasMore: false })),
+ readTerminal,
+ });
+
+ const handler = handlers.get(DL_HISTORY_MESSAGES_CHANNEL);
+ const page = await handler?.({}, { ...request, fromMs: 100 }) as { terminal: unknown };
+
+ // 页面下界是 gte(fromMs),终态探针是 gt(clearedAt)——同一窗口需 fromMs-1。
+ expect(readTerminal).toHaveBeenCalledWith('session-1', 99);
+ expect(page.terminal).toEqual({ status: 'error', createdAt: 500 });
+ });
+
+ it('normalizes a missing terminal to null and a missing fromMs to a null bound', async () => {
+ const readTerminal = vi.fn(async () => undefined);
+ register({
+ sessionExists: vi.fn(async () => true),
+ getMessages: vi.fn(async () => ({ items: [], nextCursor: null, hasMore: false })),
+ readTerminal,
+ });
+
+ const handler = handlers.get(DL_HISTORY_MESSAGES_CHANNEL);
+ const page = await handler?.({}, { ...request, fromMs: null }) as { terminal: unknown };
+
+ expect(readTerminal).toHaveBeenCalledWith('session-1', null);
+ expect(page.terminal).toBeNull();
+ });
});
diff --git a/apps/desktop/src/main/localDb/ipc/history.ts b/apps/desktop/src/main/localDb/ipc/history.ts
index c5560cf75e..fc6a1a2a65 100644
--- a/apps/desktop/src/main/localDb/ipc/history.ts
+++ b/apps/desktop/src/main/localDb/ipc/history.ts
@@ -18,6 +18,7 @@ import {
} from '../chatHistoryReader';
import { getDbClient } from '../client/current';
import { sessions } from '../schema';
+import { readLatestSessionTerminal, type SessionTerminalHint } from '../sessionTerminal';
import { requireObject, requireString, throwIpcError } from '../../utils/ipcValidate';
const VALID_AGENT_KINDS: readonly HistoryAgentKind[] = ['cc', 'codex'];
@@ -52,6 +53,7 @@ export interface RemoteHistoryMessagesRequest {
export interface RemoteHistoryIpcDeps {
sessionExists(sessionId: string): Promise<boolean>;
getMessages(params: GetMessagesParams): ReturnType<typeof getMessagesForHistory>;
+ readTerminal(sessionId: string, clearedAt: number | null): Promise<SessionTerminalHint | undefined>;
}
function nullableFiniteNumber(value: unknown, name: string): number | null {
@@ -264,16 +266,19 @@ function capReferenceHistoryPage(
};
}
+const defaultSessionExists = async (sessionId: string): Promise<boolean> => {
+ const rows = await getDbClient().drizzle
+ .select({ id: sessions.id })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ return rows.length > 0;
+};
+
const defaultDeps: RemoteHistoryIpcDeps = {
- async sessionExists(sessionId) {
- const rows = await getDbClient().drizzle
- .select({ id: sessions.id })
- .from(sessions)
- .where(eq(sessions.id, sessionId))
- .limit(1);
- return rows.length > 0;
- },
+ sessionExists: defaultSessionExists,
getMessages: getMessagesForHistory,
+ readTerminal: readLatestSessionTerminal,
};
/** Register the allowlisted, read-only remote history handler. */
@@ -295,9 +300,21 @@ export function registerRemoteHistoryIpc(deps: RemoteHistoryIpcDeps = defaultDep
cursor: request.cursor,
order: request.order,
});
+ // 终态标记与页面读取在同一次 handler 调用内完成:跨设备调用方拿到的
+ // terminal 与消息快照来自同一数据库时刻(与本机解析路径的两查询间隔
+ // 同价),不会出现「历史页读完、再探测时源端已写入更新回合的错误行」
+ // 导致的终态错配。错误正文不出被控端,只回安全标记。
+ // 页面下界是 gte(fromMs),终态探针是 gt(clearedAt)——同一窗口需 fromMs-1。
+ const terminal = await deps.readTerminal(
+ request.sessionId,
+ request.fromMs === null ? null : request.fromMs - 1,
+ );
const preserveStructuredRoles =
request.roles === null ||
request.roles.some((role) => role !== 'user' && role !== 'assistant');
- return capReferenceHistoryPage(page, request.contentCharLimit, preserveStructuredRoles);
+ return {
+ ...capReferenceHistoryPage(page, request.contentCharLimit, preserveStructuredRoles),
+ terminal: terminal ?? null,
+ };
});
}
diff --git a/apps/desktop/src/main/localDb/sessionTerminal.ts b/apps/desktop/src/main/localDb/sessionTerminal.ts
new file mode 100644
index 0000000000..fbdff298dd
--- /dev/null
+++ b/apps/desktop/src/main/localDb/sessionTerminal.ts
@@ -0,0 +1,64 @@
+/**
+ * 会话尾部终态探针。
+ *
+ * 错误行有意不进入引用消息列表:其结构化正文可能含 provider 细节或回显的请求
+ * 数据。这里只产出非敏感的安全标记,供会话引用(本地与 device-link 远程)解释
+ * 「最后一条 assistant 文本为何不完整」。本地解析与远程被控端 handler 共用同一
+ * 判定,避免两端语义分叉。
+ */
+import { and, desc, eq, gt, isNull, sql, type SQL } from 'drizzle-orm';
+import { getDbClient } from './client/current';
+import { messages } from './schema';
+
+const messageRowid = sql<number>`"messages"."rowid"`;
+
+export interface SessionTerminalHint {
+ status: 'error';
+ createdAt?: number;
+}
+
+/**
+ * Return only a non-sensitive terminal hint for a session snapshot.
+ *
+ * The marker is enough to explain why the last assistant text can be
+ * incomplete; the persisted error body never leaves this layer.
+ */
+export async function readLatestSessionTerminal(
+ sessionId: string,
+ clearedAt: number | null,
+): Promise<SessionTerminalHint | undefined> {
+ const db = getDbClient().drizzle;
+ const where: SQL<unknown>[] = [
+ eq(messages.sessionId, sessionId),
+ isNull(messages.rewindAt),
+ ];
+ if (clearedAt !== null) where.push(gt(messages.createdAt, clearedAt));
+ const [latest] = await db
+ .select({ role: messages.role, content: messages.content, createdAt: messages.createdAt })
+ .from(messages)
+ .where(and(...where))
+ .orderBy(desc(messages.createdAt), desc(messageRowid))
+ .limit(1);
+ if (latest?.role !== 'error') return undefined;
+ // An ignored error remains in the database for audit/history, but should no
+ // longer make a fresh quote look like an active failed turn.
+ if (typeof latest.content === 'string') {
+ try {
+ const parsed = JSON.parse(latest.content) as unknown;
+ if (
+ parsed &&
+ typeof parsed === 'object' &&
+ !Array.isArray(parsed) &&
+ (parsed as Record<string, unknown>).dismissed === true
+ ) {
+ return undefined;
+ }
+ } catch {
+ // Legacy non-JSON error content is treated as an undismissed error.
+ }
+ }
+ return {
+ status: 'error',
+ ...(Number.isFinite(latest.createdAt) ? { createdAt: latest.createdAt } : {}),
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.local.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.local.test.ts
index 75828be3c5..7af929d5ae 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.local.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.local.test.ts
@@ -42,7 +42,7 @@ function createDb(): Database.Database {
function insertMessage(
sqlite: Database.Database,
- input: { id: string; role: string; content: string; createdAt: number; rewindAt?: number | null },
+ input: { id: string; role: string; content: unknown; createdAt: number; rewindAt?: number | null },
): void {
sqlite.prepare(`
INSERT INTO messages (
@@ -90,6 +90,77 @@ describe('sessionReferenceResolver local visibility', () => {
expect(context.messages).toEqual([{ role: 'user', content: 'ssh history', createdAt: 101 }]);
});
+ it('marks a recent local quote whose last turn ended with an error without exposing the error body', async () => {
+ insertMessage(sqlite, { id: 'partial-user', role: 'user', content: '请继续', createdAt: 101 });
+ insertMessage(sqlite, { id: 'partial-assistant', role: 'assistant', content: '我已经看到,但', createdAt: 102 });
+ insertMessage(sqlite, {
+ id: 'turn-error',
+ role: 'error',
+ content: { message: 'provider secret should not cross the quote boundary', reason: 'turn-failed' },
+ createdAt: 103,
+ });
+
+ const [context] = await resolveSessionReferences([{ sessionId: 'local-session' }]);
+
+ expect(context.messages).toEqual([
+ { role: 'user', content: '请继续', createdAt: 101 },
+ { role: 'assistant', content: '我已经看到,但', createdAt: 102 },
+ ]);
+ expect(context.terminal).toEqual({ status: 'error', createdAt: 103 });
+ expect(JSON.stringify(context)).not.toContain('provider secret');
+ });
+
+ it('does not mark an error that the user already dismissed', async () => {
+ insertMessage(sqlite, { id: 'user', role: 'user', content: 'question', createdAt: 101 });
+ insertMessage(sqlite, { id: 'assistant', role: 'assistant', content: 'partial', createdAt: 102 });
+ insertMessage(sqlite, {
+ id: 'dismissed-error',
+ role: 'error',
+ content: { message: 'failed', dismissed: true },
+ createdAt: 103,
+ });
+
+ const [context] = await resolveSessionReferences([{ sessionId: 'local-session' }]);
+
+ expect(context.terminal).toBeUndefined();
+ });
+
+ it('does not mark an error row that was rewound out of the visible history', async () => {
+ insertMessage(sqlite, { id: 'user', role: 'user', content: 'question', createdAt: 101 });
+ insertMessage(sqlite, { id: 'assistant', role: 'assistant', content: 'partial', createdAt: 102 });
+ insertMessage(sqlite, {
+ id: 'rewound-error',
+ role: 'error',
+ content: { message: 'old failure' },
+ createdAt: 103,
+ rewindAt: 104,
+ });
+
+ const [context] = await resolveSessionReferences([{ sessionId: 'local-session' }]);
+
+ expect(context.terminal).toBeUndefined();
+ });
+
+ it('does not mark an older error when a newer visible message is the tail', async () => {
+ insertMessage(sqlite, { id: 'user', role: 'user', content: 'question', createdAt: 101 });
+ insertMessage(sqlite, {
+ id: 'error',
+ role: 'error',
+ content: { message: 'recovered failure' },
+ createdAt: 103,
+ });
+ // Same-timestamp rows use rowid as the deterministic tail tie-breaker.
+ insertMessage(sqlite, { id: 'assistant', role: 'assistant', content: 'continued', createdAt: 103 });
+
+ const [context] = await resolveSessionReferences([{ sessionId: 'local-session' }]);
+
+ expect(context.messages).toEqual([
+ { role: 'user', content: 'question', createdAt: 101 },
+ { role: 'assistant', content: 'continued', createdAt: 103 },
+ ]);
+ expect(context.terminal).toBeUndefined();
+ });
+
// 深链是可复制的字符串:控制端生成的 `?device=` 链接被带回归属设备本机
// 粘贴发送时,ref.deviceId 指向本机自己——必须按本地会话解析,不得对
// 自己发起 device-link 隧道。
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts
index a670fe80b9..b7ec5116fd 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionReferenceResolver.test.ts
@@ -397,4 +397,95 @@ describe('sessionReferenceResolver', () => {
})))).rejects.toMatchObject({ code: 'SESSION_REFERENCE_INVALID' });
expect(remoteInvoke).not.toHaveBeenCalled();
});
+
+ it('attaches the validated first-page terminal without leaking the error body', async () => {
+ remoteInvoke
+ .mockResolvedValueOnce({ ok: true, result: { id: 's-1', title: 'Session' } })
+ .mockResolvedValueOnce({
+ ok: true,
+ result: {
+ items: [
+ { id: 'm-2', sessionId: 's-1', role: 'assistant', content: '我已经看到,但', createdAt: 102 },
+ { id: 'm-1', sessionId: 's-1', role: 'user', content: '请继续', createdAt: 101 },
+ ],
+ hasMore: false,
+ nextCursor: null,
+ terminal: {
+ status: 'error',
+ createdAt: 103,
+ message: 'provider secret must not cross the quote boundary',
+ injected: 'junk',
+ },
+ },
+ });
+
+ const [context] = await resolveSessionReferences([{ sessionId: 's-1', deviceId: 'dev-1' }]);
+
+ expect(context.terminal).toEqual({ status: 'error', createdAt: 103 });
+ expect(JSON.stringify(context)).not.toContain('provider secret');
+ expect(JSON.stringify(context)).not.toContain('junk');
+ // 终态与历史页同一次响应到达,没有额外的探测往返。
+ expect(remoteInvoke).toHaveBeenCalledTimes(2);
+ });
+
+ it('degrades to no terminal when the source page predates the terminal field', async () => {
+ remoteInvoke
+ .mockResolvedValueOnce({ ok: true, result: { id: 's-1' } })
+ .mockResolvedValueOnce(historyPage([
+ { id: 'm-1', sessionId: 's-1', role: 'assistant', content: 'partial', createdAt: 1 },
+ ]));
+
+ const [context] = await resolveSessionReferences([{ sessionId: 's-1', deviceId: 'dev-1' }]);
+
+ expect(context.messages).toHaveLength(1);
+ expect(context.terminal).toBeUndefined();
+ });
+
+ it('ignores malformed terminal payloads from the source device', async () => {
+ remoteInvoke
+ .mockResolvedValueOnce({ ok: true, result: { id: 's-1' } })
+ .mockResolvedValueOnce({
+ ok: true,
+ result: {
+ items: [{ id: 'm-1', sessionId: 's-1', role: 'assistant', content: 'partial', createdAt: 1 }],
+ hasMore: false,
+ nextCursor: null,
+ terminal: { status: 'fatal', body: 'crafted' },
+ },
+ });
+
+ const [context] = await resolveSessionReferences([{ sessionId: 's-1', deviceId: 'dev-1' }]);
+
+ expect(context.terminal).toBeUndefined();
+ });
+
+ it('ignores the page terminal for anchor quotes', async () => {
+ remoteInvoke
+ .mockResolvedValueOnce({ ok: true, result: { id: 's-1', title: 'Session' } })
+ .mockResolvedValueOnce({
+ ok: true,
+ result: [{ sessionId: 's-1', clientId: 'c-1', id: 'm-2', rowid: 2, role: 'assistant', content: 'anchor', createdAt: 2 }],
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ result: {
+ items: [{ id: 'm-1', sessionId: 's-1', role: 'user', content: 'before', createdAt: 1 }],
+ hasMore: false,
+ nextCursor: null,
+ terminal: { status: 'error', createdAt: 9 },
+ },
+ })
+ .mockResolvedValueOnce(historyPage([
+ { id: 'm-3', sessionId: 's-1', role: 'assistant', content: 'after', createdAt: 3 },
+ ]));
+
+ const [context] = await resolveSessionReferences([{
+ sessionId: 's-1',
+ deviceId: 'dev-1',
+ messageClientId: 'c-1',
+ }]);
+
+ expect(context.range).toBe('around-anchor');
+ expect(context.terminal).toBeUndefined();
+ });
});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 934c553254..357318379a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -7526,6 +7526,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
) {
throwIpcError('SESSION_REFERENCE_UNAVAILABLE', 'remote session reference snapshot does not match the request');
}
+ if (context.terminal !== undefined) {
+ const terminal = context.terminal;
+ if (
+ !terminal ||
+ typeof terminal !== 'object' ||
+ Array.isArray(terminal) ||
+ terminal.status !== 'error' ||
+ (
+ terminal.createdAt !== undefined &&
+ (typeof terminal.createdAt !== 'number' || !Number.isFinite(terminal.createdAt))
+ )
+ ) {
+ throwIpcError('SESSION_REFERENCE_UNAVAILABLE', 'remote session reference terminal status is invalid');
+ }
+ // Strip unknown fields at this trust boundary. The marker is
+ // intentionally status-only; provider error details must not cross
+ // into the model prompt through a crafted remote snapshot.
+ context.terminal = {
+ status: 'error',
+ ...(terminal.createdAt !== undefined ? { createdAt: terminal.createdAt } : {}),
+ };
+ }
totalMessages += context.messages.length;
for (const message of context.messages) {
if (!message || (message.role !== 'user' && message.role !== 'assistant') || typeof message.content !== 'string') {
diff --git a/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts b/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts
index b60b083e69..094eb9a3f3 100644
--- a/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionReferenceResolver.ts
@@ -9,6 +9,7 @@ import { DL_HISTORY_MESSAGES_CHANNEL } from '@cindy/device-link';
import { getSelfDeviceId, remoteInvoke as invokeRemote } from '../device-link/index.js';
import { getDbClient } from '../localDb/client/current.js';
import { messages, sessions } from '../localDb/schema.js';
+import { readLatestSessionTerminal } from '../localDb/sessionTerminal.js';
import { messageToCamel } from '../localDb/mapper.js';
import { isSyntheticTriggerText } from '../../shared/interruptedTurn.js';
import {
@@ -16,6 +17,7 @@ import {
type AgentInputSessionRef,
type AgentInputSessionReferenceContext,
type AgentInputSessionReferenceMessage,
+ type AgentInputSessionReferenceTerminal,
} from '../../shared/agentInputQueue.js';
export const MAX_SESSION_REFERENCES = 8;
@@ -365,6 +367,19 @@ async function resolveLocal(
.limit(1);
if (!session) throw new SessionReferenceError('SESSION_REFERENCE_NOT_FOUND', `找不到本机会话 ${ref.sessionId}`);
const loaded = await readLocalRows(ref, messageLimit, session.clearedAt ?? null);
+ // A recent local snapshot may legitimately end at a partial assistant
+ // message when the turn failed. Preserve only a safe status marker; never
+ // inject the persisted error body into the quoted context.
+ let terminal: AgentInputSessionReferenceTerminal | undefined;
+ if (!ref.messageClientId) {
+ try {
+ terminal = await readLatestSessionTerminal(ref.sessionId, session.clearedAt ?? null);
+ } catch {
+ // Terminal status is diagnostic metadata; a transient read failure must
+ // not make an otherwise valid session reference fail closed.
+ terminal = undefined;
+ }
+ }
const mappedWithAnchor = loaded.rows
.map((row) => ({ message: toReferenceMessage(row), isAnchor: row.clientId === ref.messageClientId }))
.filter((entry): entry is { message: AgentInputSessionReferenceMessage; isAnchor: boolean } => entry.message !== null);
@@ -389,6 +404,7 @@ async function resolveLocal(
range: ref.messageClientId ? 'around-anchor' : 'recent',
messageCount: fitted.messages.length,
truncated: loaded.sourceTruncated || fitted.truncated,
+ ...(terminal ? { terminal } : {}),
},
usedTokens: fitted.usedTokens,
};
@@ -425,6 +441,20 @@ interface RemoteHistoryPage {
items: Record<string, unknown>[];
hasMore: boolean;
nextCursor: RemoteHistoryCursor | null;
+ terminal: AgentInputSessionReferenceTerminal | undefined;
+}
+
+/** Rebuild the optional terminal marker from validated fields only (trust boundary). */
+function parseRemoteTerminal(value: unknown): AgentInputSessionReferenceTerminal | undefined {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
+ const record = value as Record<string, unknown>;
+ if (record.status !== 'error') return undefined;
+ return {
+ status: 'error',
+ ...(typeof record.createdAt === 'number' && Number.isFinite(record.createdAt)
+ ? { createdAt: record.createdAt }
+ : {}),
+ };
}
function parseRemoteHistoryPage(ref: AgentInputSessionRef, value: unknown): RemoteHistoryPage {
@@ -439,6 +469,7 @@ function parseRemoteHistoryPage(ref: AgentInputSessionRef, value: unknown): Remo
items: page.items.filter((row): row is Record<string, unknown> =>
!!row && typeof row === 'object' && !Array.isArray(row) && row.sessionId === ref.sessionId),
hasMore: page.hasMore,
+ terminal: parseRemoteTerminal(page.terminal),
nextCursor: page.nextCursor === null || page.nextCursor === undefined
? null
: (() => {
@@ -511,9 +542,17 @@ async function readRemoteHistory(
order: 'asc' | 'desc',
fromMs: number | null,
cursor: RemoteHistoryCursor | null = null,
-): Promise<{ items: Record<string, unknown>[]; sourceTruncated: boolean }> {
+): Promise<{
+ items: Record<string, unknown>[];
+ sourceTruncated: boolean;
+ terminal: AgentInputSessionReferenceTerminal | undefined;
+}> {
const items: Record<string, unknown>[] = [];
let sourceTruncated = false;
+ // 被控端把 terminal 与页面在同一 handler 调用内算好,只有第一页的标记
+ // 与本次快照同源;后续翻页捎带的标记忽略。
+ let terminal: AgentInputSessionReferenceTerminal | undefined;
+ let firstPage = true;
const seenCursors = new Set<string>();
while (true) {
const response = await invokeRemote(ref.deviceId!, DL_HISTORY_MESSAGES_CHANNEL, [
@@ -521,6 +560,10 @@ async function readRemoteHistory(
]);
if (response.ok !== true) remoteFailure(ref, response);
const page = parseRemoteHistoryPage(ref, response.result);
+ if (firstPage) {
+ terminal = page.terminal;
+ firstPage = false;
+ }
items.push(...page.items);
sourceTruncated ||= remoteRowsWereTrimmed(page.items);
const visibleCount = items.reduce((count, row) => count + (toReferenceMessage(row) ? 1 : 0), 0);
@@ -539,6 +582,7 @@ async function readRemoteHistory(
return {
items,
sourceTruncated: sourceTruncated || (limit === 0 && items.length > 0),
+ terminal,
};
}
@@ -569,9 +613,13 @@ async function resolveRemote(
let mapped: AgentInputSessionReferenceMessage[];
let anchorIndex: number | undefined;
let sourceTruncated = false;
+ // 终态标记由被控端与首个历史页在同一 handler 调用内算好(见
+ // readRemoteHistory),与消息快照天然同源;锚点路径不带终态(与本地一致)。
+ let terminal: AgentInputSessionReferenceTerminal | undefined;
try {
if (!ref.messageClientId) {
const page = await readRemoteHistory(ref, messageLimit, 'desc', clearedAt);
+ terminal = page.terminal;
const visibleRows = page.items
.map(toReferenceMessage)
.filter((row): row is AgentInputSessionReferenceMessage => row !== null)
@@ -657,6 +705,7 @@ async function resolveRemote(
range: ref.messageClientId ? 'around-anchor' : 'recent',
messageCount: fitted.messages.length,
truncated: sourceTruncated || fitted.truncated,
+ ...(terminal ? { terminal } : {}),
},
usedTokens: fitted.usedTokens,
};
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index 583281315f..54d9e61289 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -61,6 +61,19 @@ export interface AgentInputSessionReferenceMessage {
createdAt?: number;
}
+/**
+ * Safe terminal-state hint for a quoted session.
+ *
+ * The actual persisted error row is intentionally not copied into the quote:
+ * it may contain provider-specific or user-sensitive details. This additive
+ * marker lets the receiving agent distinguish a genuinely interrupted turn
+ * from a response that simply ended at the last visible text.
+ */
+export interface AgentInputSessionReferenceTerminal {
+ status: 'error';
+ createdAt?: number;
+}
+
export interface AgentInputSessionReferenceContext {
sessionId: string;
title?: string;
@@ -71,6 +84,8 @@ export interface AgentInputSessionReferenceContext {
range: 'recent' | 'around-anchor';
messageCount: number;
truncated: boolean;
+ /** Present only when the recent snapshot (local or device-link) ends in a persisted turn error. */
+ terminal?: AgentInputSessionReferenceTerminal;
}
export interface AgentInputImageRef {
diff --git a/apps/mobile/src/__tests__/sessionReferences.test.ts b/apps/mobile/src/__tests__/sessionReferences.test.ts
index 77b85e311d..c8bbbd7abc 100644
--- a/apps/mobile/src/__tests__/sessionReferences.test.ts
+++ b/apps/mobile/src/__tests__/sessionReferences.test.ts
@@ -541,4 +541,72 @@ describe('resolveMobileSessionReferences', () => {
)).rejects.toMatchObject({ code: 'SESSION_REFERENCE_INVALID' });
expect(neverInvoke).not.toHaveBeenCalled();
});
+
+ it('attaches the validated first-page terminal without leaking the source error body', async () => {
+ const invoke = asInvoke(async (_deviceId, channel, args) => {
+ if (channel === 'local-db:sessions:get') return { id: args[0], title: 'Source' };
+ if (channel === DL_HISTORY_MESSAGES_CHANNEL) {
+ return {
+ items: [message('s1', '1', 'c1', '半截回复', 'assistant')],
+ hasMore: false,
+ terminal: {
+ status: 'error',
+ createdAt: 103,
+ message: 'provider secret must not cross the quote boundary',
+ injected: 'junk',
+ },
+ };
+ }
+ throw new Error(`unexpected channel ${channel}`);
+ });
+
+ const [context] = await resolveMobileSessionReferences([
+ { sessionId: 's1', deviceId: 'dev-a' },
+ ], invoke);
+
+ expect(context.terminal).toEqual({ status: 'error', createdAt: 103 });
+ const serialized = serializeMobileSessionReferencePayload([context]);
+ expect(serialized).not.toContain('provider secret');
+ expect(serialized).not.toContain('junk');
+ });
+
+ it('degrades to no terminal when the source page predates the terminal field', async () => {
+ const invoke = asInvoke(async (_deviceId, channel, args) => {
+ if (channel === 'local-db:sessions:get') return { id: args[0], title: 'Source' };
+ if (channel === DL_HISTORY_MESSAGES_CHANNEL) {
+ return {
+ items: [message('s1', '1', 'c1', 'partial', 'assistant')],
+ hasMore: false,
+ };
+ }
+ throw new Error(`unexpected channel ${channel}`);
+ });
+
+ const [context] = await resolveMobileSessionReferences([
+ { sessionId: 's1', deviceId: 'dev-a' },
+ ], invoke);
+
+ expect(context.messages).toHaveLength(1);
+ expect(context.terminal).toBeUndefined();
+ });
+
+ it('ignores the page terminal for anchor quotes', async () => {
+ const invoke = asInvoke(async (_deviceId, channel, args) => {
+ if (channel === 'local-db:sessions:get') return { id: args[0], title: 'Anchored' };
+ if (channel === 'local-db:messages:around-client-id') {
+ return [message('s1', '1', 'anchor', 'anchor body', 'user', 1_000)];
+ }
+ if (channel === DL_HISTORY_MESSAGES_CHANNEL) {
+ return { items: [], hasMore: false, terminal: { status: 'error', createdAt: 9 } };
+ }
+ return null;
+ });
+
+ const [context] = await resolveMobileSessionReferences([
+ { sessionId: 's1', messageClientId: 'anchor', deviceId: 'dev-a' },
+ ], invoke);
+
+ expect(context.range).toBe('around-anchor');
+ expect(context.terminal).toBeUndefined();
+ });
});
diff --git a/apps/mobile/src/session/sessionReferences.ts b/apps/mobile/src/session/sessionReferences.ts
index ae2dbf133e..bfc1cbfd00 100644
--- a/apps/mobile/src/session/sessionReferences.ts
+++ b/apps/mobile/src/session/sessionReferences.ts
@@ -32,6 +32,19 @@ export interface MobileSessionReferenceMessage {
createdAt?: number;
}
+/**
+ * Safe terminal-state hint for a quoted session.
+ *
+ * The persisted error row is intentionally not copied into the quote: its
+ * body may contain provider-specific details. This additive marker lets the
+ * receiving agent distinguish a genuinely interrupted turn from a response
+ * that simply ended at the last visible text.
+ */
+export interface MobileSessionReferenceTerminal {
+ status: 'error';
+ createdAt?: number;
+}
+
export interface MobileSessionReferenceContext {
sessionId: string;
title?: string;
@@ -42,6 +55,8 @@ export interface MobileSessionReferenceContext {
range: 'recent' | 'around-anchor';
messageCount: number;
truncated: boolean;
+ /** Present only when the recent snapshot ends in a persisted turn error on the source device. */
+ terminal?: MobileSessionReferenceTerminal;
}
/** 展示安全的落库摘要;不含任何被引用消息正文。 */
@@ -387,6 +402,20 @@ interface RemoteHistoryPage {
items: Record<string, unknown>[];
hasMore: boolean;
nextCursor: RemoteHistoryCursor | null;
+ terminal: MobileSessionReferenceTerminal | undefined;
+}
+
+/** Rebuild the optional terminal marker from validated fields only (trust boundary). */
+function parseRemoteTerminal(value: unknown): MobileSessionReferenceTerminal | undefined {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
+ const record = value as Record<string, unknown>;
+ if (record.status !== 'error') return undefined;
+ return {
+ status: 'error',
+ ...(typeof record.createdAt === 'number' && Number.isFinite(record.createdAt)
+ ? { createdAt: record.createdAt }
+ : {}),
+ };
}
function parseRemoteHistoryPage(ref: MobileSessionReference, value: unknown): RemoteHistoryPage {
@@ -407,6 +436,7 @@ function parseRemoteHistoryPage(ref: MobileSessionReference, value: unknown): Re
items: page.items.filter((row): row is Record<string, unknown> =>
!!row && typeof row === 'object' && !Array.isArray(row) && row.sessionId === ref.sessionId),
hasMore: page.hasMore,
+ terminal: parseRemoteTerminal(page.terminal),
nextCursor: page.nextCursor === null || page.nextCursor === undefined
? null
: (() => {
@@ -480,15 +510,27 @@ async function readRemoteHistory(
order: 'asc' | 'desc',
fromMs: number | null,
cursor: RemoteHistoryCursor | null = null,
-): Promise<{ items: Record<string, unknown>[]; sourceTruncated: boolean }> {
+): Promise<{
+ items: Record<string, unknown>[];
+ sourceTruncated: boolean;
+ terminal: MobileSessionReferenceTerminal | undefined;
+}> {
const items: Record<string, unknown>[] = [];
let sourceTruncated = false;
+ // 被控端把 terminal 与页面在同一 handler 调用内算好,只有第一页的标记
+ // 与本次快照同源;后续翻页捎带的标记忽略。
+ let terminal: MobileSessionReferenceTerminal | undefined;
+ let firstPage = true;
const seenCursors = new Set<string>();
while (true) {
const rawPage = await invokeSource<unknown>(invoke, ref, DL_HISTORY_MESSAGES_CHANNEL, [
remoteHistoryRequest(ref, Math.max(1, limit), order, fromMs, cursor),
]);
const page = parseRemoteHistoryPage(ref, rawPage);
+ if (firstPage) {
+ terminal = page.terminal;
+ firstPage = false;
+ }
items.push(...page.items);
sourceTruncated ||= remoteRowsWereTrimmed(page.items);
const visibleCount = items.reduce((count, row) => count + (toReferenceMessage(row) ? 1 : 0), 0);
@@ -507,6 +549,7 @@ async function readRemoteHistory(
return {
items,
sourceTruncated: sourceTruncated || (limit === 0 && items.length > 0),
+ terminal,
};
}
@@ -596,8 +639,12 @@ async function resolveRemoteReference(
let mapped: MobileSessionReferenceMessage[];
let anchorIndex: number | undefined;
let sourceTruncated = false;
+ // 终态标记由被控端与首个历史页在同一 handler 调用内算好(见
+ // readRemoteHistory),与消息快照天然同源;锚点路径不带终态。
+ let terminal: MobileSessionReferenceTerminal | undefined;
if (!ref.messageClientId) {
const page = await readRemoteHistory(invoke, ref, messageLimit, 'desc', clearedAt);
+ terminal = page.terminal;
const visibleRows = page.items
.map(toReferenceMessage)
.filter((row): row is MobileSessionReferenceMessage => row !== null)
@@ -684,6 +731,7 @@ async function resolveRemoteReference(
range: ref.messageClientId ? 'around-anchor' : 'recent',
messageCount: fitted.messages.length,
truncated: sourceTruncated || fitted.truncated,
+ ...(terminal ? { terminal } : {}),
},
usedTokens: fitted.usedTokens,
};
diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.ts
index 7d353a5c20..0c9e7b4c0e 100644
--- a/packages/anthropic-compat-proxy/src/server.test.ts
+++ b/packages/anthropic-compat-proxy/src/server.test.ts
@@ -1921,6 +1921,7 @@ describe('anthropic-compat-proxy 客户端中断传播', () => {
it('客户端在流式响应中途断开时,同步掐掉上游请求(费用泄漏止血)', async () => {
let sawAbort!: () => void;
const upstreamAborted = new Promise<void>((r) => { sawAbort = r; });
+ const errorLogs: string[] = [];
const upstream = await startFakeUpstream((_idx, _body, res) => {
res.writeHead(200, { 'content-type': 'text/event-stream' });
res.write('event: message_start\ndata: {}\n\n');
@@ -1929,7 +1930,11 @@ describe('anthropic-compat-proxy 客户端中断传播', () => {
res.on('close', () => sawAbort());
});
upstreamClose = upstream.close;
- proxy = await createAnthropicCompatProxy({ upstream: upstream.url, transformRequest: [] });
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ logger: { error: (msg) => { errorLogs.push(msg); } },
+ });
const controller = new AbortController();
const res = await fetch(`${proxy.url}/v1/messages`, {
@@ -1944,6 +1949,92 @@ describe('anthropic-compat-proxy 客户端中断传播', () => {
await reader.read();
controller.abort();
await upstreamAborted;
+ expect(errorLogs.filter((m) => m.includes('upstream response stream error'))).toHaveLength(0);
+ });
+
+ it('透明重试后的上游 2xx SSE 中断时,立即收口且旧 listener 不误报客户端断开', async () => {
+ const errorLogs: Array<{ msg: string; ctx?: Record<string, unknown> }> = [];
+ const infoLogs: string[] = [];
+ const observerErrors: string[] = [];
+ let observerEnds = 0;
+ const upstream = await startFakeUpstream((idx, _body, res) => {
+ if (idx === 0) {
+ res.writeHead(400, { 'content-type': 'application/json' });
+ res.end(ENC_ERROR_BODY);
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
+ res.write('event: message_start\ndata: {}\n\n');
+ // 不发送 end,模拟上游生成过程中连接被对端掐断。Node 可能发
+ // `aborted`、`error`、`close` 中的一个或多个,代理必须幂等收口。
+ setTimeout(() => res.destroy(), 50);
+ });
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ recoveryRules: [createEncryptedContentRecoveryRule({ enabled: () => true })],
+ logger: {
+ info: (msg) => infoLogs.push(msg),
+ error: (msg, ctx) => errorLogs.push({ msg, ctx }),
+ },
+ responseObserver: () => ({
+ onEnd: () => { observerEnds += 1; },
+ onError: (err) => { observerErrors.push(err.message); },
+ }),
+ });
+
+ const controller = new AbortController();
+ let responseStatus: number | null = null;
+ let clientError: unknown = null;
+ const operation = fetch(`${proxy.url}/v1/messages?api_key=must-not-appear-in-logs`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ model: 'test-model',
+ input: [{ type: 'reasoning', encrypted_content: 'gAAAsecret' }],
+ }),
+ signal: controller.signal,
+ }).then(async (res) => {
+ responseStatus = res.status;
+ await res.text();
+ }).catch((err: unknown) => {
+ // destroy() 后 undici 通常会以 body read error 收口,这正是期望的
+ // “立即失败”语义;测试只关心它不能悬挂到 watchdog。
+ clientError = err;
+ });
+ let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
+ const outcome = await Promise.race([
+ operation.then(() => 'settled' as const),
+ new Promise<'timeout'>((resolve) => {
+ timeoutHandle = setTimeout(() => resolve('timeout'), 1000);
+ }),
+ ]);
+ if (timeoutHandle !== undefined) clearTimeout(timeoutHandle);
+ if (outcome === 'timeout') controller.abort();
+
+ expect(outcome).toBe('settled');
+ expect(responseStatus).toBe(200);
+ expect(clientError).toBeInstanceOf(Error);
+ expect(upstream.bodies).toHaveLength(2);
+ expect(infoLogs.filter((m) => m.includes('client disconnected'))).toHaveLength(0);
+ const responseFailures = errorLogs.filter((entry) => entry.msg === 'upstream response stream error');
+ expect(responseFailures).toHaveLength(1);
+ expect(responseFailures[0].ctx).toMatchObject({
+ status: 200,
+ reason: expect.stringMatching(/^(error|aborted|close)$/),
+ bytes: expect.any(Number),
+ lastChunkBytes: expect.any(Number),
+ lastChunkAt: expect.any(Number),
+ });
+ expect(responseFailures[0].ctx?.path).toBe('/v1/messages');
+ expect(JSON.stringify(responseFailures[0].ctx)).not.toContain('must-not-appear-in-logs');
+ expect(Number(responseFailures[0].ctx?.bytes)).toBeGreaterThan(0);
+ expect(responseFailures[0].ctx).not.toHaveProperty('body');
+ expect(responseFailures[0].ctx).not.toHaveProperty('requestBody');
+ expect(responseFailures[0].ctx).not.toHaveProperty('chunk');
+ expect(observerErrors).toHaveLength(1);
+ expect(observerEnds).toBe(0);
});
it('正常完成的响应不受影响:不误判为客户端断开,连接复用下后续请求照常', async () => {
@@ -1956,10 +2047,15 @@ describe('anthropic-compat-proxy 客户端中断传播', () => {
// "client disconnected mid-response" 的中断传播路径(否则每笔请求都会对
// 完成态上游请求调 destroy 并刷一条误导日志)。
const infoLogs: string[] = [];
+ const errorLogs: string[] = [];
proxy = await createAnthropicCompatProxy({
upstream: upstream.url,
transformRequest: [],
- logger: { info: (msg) => { infoLogs.push(msg); } },
+ // 此测试同时确保 upstream end 后迟到的 request/response error 不会重复收口。
+ logger: {
+ info: (msg) => { infoLogs.push(msg); },
+ error: (msg) => { errorLogs.push(msg); },
+ },
});
const r1 = await post(proxy.url, { model: 'test-model' });
@@ -1968,6 +2064,7 @@ describe('anthropic-compat-proxy 客户端中断传播', () => {
expect(r2.status).toBe(200);
expect(upstream.bodies).toHaveLength(2);
expect(infoLogs.filter((m) => m.includes('client disconnected'))).toHaveLength(0);
+ expect(errorLogs.filter((m) => m.includes('upstream response stream error'))).toHaveLength(0);
});
});
diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.ts
index 921a36ec03..5b5eddb924 100644
--- a/packages/anthropic-compat-proxy/src/server.ts
+++ b/packages/anthropic-compat-proxy/src/server.ts
@@ -722,18 +722,68 @@ function forward(
// writableEnded 为 false —— 那不是客户端断开,不该打断开日志/置 clientAborted,
// 否则排查上游故障时日志会把因果指向客户端。destroy 前置位此标记跳过。
let proxyDestroyedClient = false;
+ // 一个请求可能同时收到 upstream response 的 `aborted` + `error`(或 `close`),
+ // 也可能在 response error 之后再收到 upstreamReq error。所有这些事件都只
+ // 能把 clientRes 收口一次;否则第二个事件会重复 destroy / 重复刷错误日志。
+ let upstreamFailureHandled = false;
+ // `end` 与 `close` 的事件顺序由 Node stream 决定,不能用 clientRes.writableEnded
+ // 判断上游是否正常结束:上游 `end` listener 执行时 pipe 尚未调用 clientRes.end()。
+ // 这个状态还用于屏蔽 error/aborted 在正常 end 后的迟到事件。
+ let upstreamResponseTerminal: 'end' | 'error' | 'aborted' | 'close' | 'client-aborted' | null = null;
+ // response 已经开始后,同一个 socket 故障在不同 Node/平台上可能先落到
+ // upstreamReq.error 或 upstreamRes.error。request 侧通过这个回调汇入当前
+ // response 的终态处理,保证 observer 与下游收口语义不受事件先后影响。
+ let failActiveResponse: ((err: unknown) => void) | null = null;
+
+ const finishClientAfterUpstreamFailure = (err: Error, message = `upstream stream error: ${String(err)}`): boolean => {
+ if (
+ clientAborted ||
+ proxyDestroyedClient ||
+ upstreamFailureHandled ||
+ clientRes.destroyed ||
+ clientRes.writableEnded
+ ) {
+ return false;
+ }
+ upstreamFailureHandled = true;
+ // `destroy()` / `end()` 都会触发 clientRes.close;先标记来源,避免 close listener
+ // 把代理自己收口的故障误报成“client disconnected”。
+ proxyDestroyedClient = true;
+ if (!clientRes.headersSent) {
+ clientRes.writeHead(502, { 'content-type': 'application/json' });
+ clientRes.end(JSON.stringify({
+ error: { type: 'proxy_error', message },
+ }));
+ } else {
+ // 已经把上游的部分响应发给客户端时,不能 end 一个看似完整的 SSE。
+ // destroy 让 Claude/SDK 明确收到截断连接并立即失败,而不是把半截流当成功。
+ clientRes.destroy(err);
+ }
+ return true;
+ };
+
clientRes.on('close', () => {
- if (proxyDestroyedClient || clientRes.writableEnded) return;
+ // 透明重试的上一笔 forward 也保留着 close listener;它的上游已经 end,
+ // 后一笔若因上游故障 destroy clientRes,不能被旧 listener 误报成客户端断开。
+ if (proxyDestroyedClient || upstreamResponseTerminal === 'end' || clientRes.writableEnded) return;
clientAborted = true;
+ if (upstreamResponseTerminal === null) upstreamResponseTerminal = 'client-aborted';
logger.info?.('client disconnected mid-response — aborting upstream request', {
reqId,
method,
- path: upstreamPath,
+ path: upstreamPathname,
});
upstreamReq.destroy(new Error('client aborted before response completed'));
});
upstreamReq.on('response', (upstreamRes) => {
+ // 请求已经因客户端断开或另一条 upstream error 路径收口时,不要再向同一个
+ // ServerResponse 写 header/pipe;恢复上游读取以释放 socket。
+ if (clientAborted || upstreamFailureHandled || clientRes.destroyed || upstreamResponseTerminal === 'client-aborted') {
+ upstreamRes.resume();
+ return;
+ }
+
// status + headers 透传(过滤掉 transfer-encoding 让 Node 自己处理 chunked)
const respHeaders: Record<string, string | string[]> = {};
for (const [k, v] of Object.entries(upstreamRes.headers)) {
@@ -753,8 +803,39 @@ function forward(
: [];
if (activeRules.length > 0) {
const chunks: Buffer[] = [];
- upstreamRes.on('data', (chunk: Buffer) => chunks.push(chunk));
+ const failBufferedResponse = (
+ reason: 'error' | 'aborted' | 'close',
+ rawError?: unknown,
+ ): void => {
+ if (upstreamResponseTerminal !== null) return;
+ upstreamResponseTerminal = reason;
+ if (clientAborted || clientRes.destroyed) return;
+ const err = rawError instanceof Error
+ ? rawError
+ : new Error(rawError === undefined
+ ? `upstream response ${reason} before completion`
+ : String(rawError));
+ logger.error?.('upstream response stream error (during 400 buffering)', {
+ reqId,
+ err: String(err),
+ reason,
+ status,
+ bytes: chunks.reduce((sum, chunk) => sum + chunk.length, 0),
+ });
+ // 400/422 buffering never creates a responseObserver sink; only the
+ // streaming path below owns observer start/data/end/error callbacks.
+ finishClientAfterUpstreamFailure(err);
+ };
+ failActiveResponse = (err) => failBufferedResponse('error', err);
+
+ upstreamRes.on('data', (chunk: Buffer) => {
+ if (upstreamResponseTerminal !== null) return;
+ chunks.push(chunk);
+ });
upstreamRes.on('end', () => {
+ if (upstreamResponseTerminal !== null) return;
+ upstreamResponseTerminal = 'end';
+ if (clientAborted || clientRes.destroyed || upstreamFailureHandled) return;
const errBody = Buffer.concat(chunks);
// 先按 content-encoding 解压一次 —— 规则 matches / errorType / body dump 都吃解压后的字节。
// node:http 不自动解压; 上游若 gzip/br 压缩, 直接对压缩字节跑 regex 会漏判, 透明重试就不触发。
@@ -851,16 +932,13 @@ function forward(
}
clientRes.end(errBody);
});
- upstreamRes.on('error', (err) => {
- if (clientAborted) return;
- logger.error?.('upstream response stream error (during 400 buffering)', { reqId, err: String(err) });
- if (!clientRes.headersSent) {
- clientRes.writeHead(502, { 'content-type': 'application/json' });
- clientRes.end(JSON.stringify({ error: { type: 'proxy_error', message: `upstream stream error: ${String(err)}` } }));
- } else {
- proxyDestroyedClient = true;
- clientRes.destroy(err);
- }
+ upstreamRes.on('error', (err) => failBufferedResponse('error', err));
+ // IncomingMessage 在连接被对端提前掐断时可能只发 `aborted`,不一定随后发
+ // `error`;两条事件都接入同一个幂等收口。
+ upstreamRes.on('aborted', () => failBufferedResponse('aborted'));
+ upstreamRes.on('close', () => {
+ if (upstreamResponseTerminal !== null || upstreamRes.complete) return;
+ failBufferedResponse('close');
});
return;
}
@@ -914,6 +992,38 @@ function forward(
}
};
+ let lastChunkBytes = 0;
+ let lastChunkAt: number | null = null;
+ const failStreamingResponse = (
+ reason: 'error' | 'aborted' | 'close',
+ rawError?: unknown,
+ ): void => {
+ if (upstreamResponseTerminal !== null) return;
+ upstreamResponseTerminal = reason;
+ // 客户端主动停止是预期的取消路径,不应再通知 observer 为上游故障。
+ if (clientAborted || clientRes.destroyed) return;
+ const err = rawError instanceof Error
+ ? rawError
+ : new Error(rawError === undefined
+ ? `upstream response ${reason} before completion`
+ : String(rawError));
+ observerError(err);
+ logger.error?.('upstream response stream error', {
+ reqId,
+ method,
+ // query 可能携带供应商签名或 token;生命周期日志只保留 pathname。
+ path: upstreamPathname,
+ status,
+ err: String(err),
+ reason,
+ bytes: totalBytes,
+ lastChunkBytes,
+ lastChunkAt,
+ });
+ finishClientAfterUpstreamFailure(err);
+ };
+ failActiveResponse = (err) => failStreamingResponse('error', err);
+
clientRes.writeHead(status, upstreamRes.statusMessage, respHeaders);
// 收 body: 总字节始终累加;status >= 400 时额外收集前 ERROR_RESPONSE_DUMP_MAX_BYTES
@@ -924,7 +1034,10 @@ function forward(
const errBuf: Buffer[] = [];
let errBufBytes = 0;
upstreamRes.on('data', (chunk: Buffer) => {
+ if (upstreamResponseTerminal !== null) return;
totalBytes += chunk.length;
+ lastChunkBytes = chunk.length;
+ lastChunkAt = Date.now();
observerData(chunk);
if (collectErrBody && errBufBytes < ERROR_RESPONSE_DUMP_MAX_BYTES) {
const remain = ERROR_RESPONSE_DUMP_MAX_BYTES - errBufBytes;
@@ -933,6 +1046,9 @@ function forward(
}
});
upstreamRes.on('end', () => {
+ if (upstreamResponseTerminal !== null) return;
+ upstreamResponseTerminal = 'end';
+ if (clientAborted || clientRes.destroyed || upstreamFailureHandled) return;
// 4xx/5xx 用 warn 级别冒泡, 默认只记低风险摘要 (status / content-type / bytes / errorType),
// 完整 body 只在 debug 级别下才进日志 —— 避免 release 把上游错误体里可能回显的请求字段
// 静默落盘到用户磁盘。debug 关时 isDebugEnabled 提前返 false, 不付 dump 字符串构造开销。
@@ -968,8 +1084,11 @@ function forward(
}
observerEnd();
});
- upstreamRes.on('error', (err) => {
- observerError(err instanceof Error ? err : new Error(String(err)));
+ upstreamRes.on('error', (err) => failStreamingResponse('error', err));
+ upstreamRes.on('aborted', () => failStreamingResponse('aborted'));
+ upstreamRes.on('close', () => {
+ if (upstreamResponseTerminal !== null || upstreamRes.complete) return;
+ failStreamingResponse('close');
});
upstreamRes.pipe(clientRes); // ← 字节级 pipe,SSE 零延迟的命脉('data' 只是计数+错误体收集, 不影响流)
@@ -978,21 +1097,27 @@ function forward(
upstreamReq.on('error', (err) => {
// 客户端主动断开触发的 destroy 是预期路径:客户端已不在,不写 502、不按
// 上游故障记 error(上面 'close' 处已记过 info)。
- if (clientAborted) return;
+ if (
+ clientAborted ||
+ upstreamFailureHandled ||
+ upstreamResponseTerminal === 'end' ||
+ clientRes.destroyed ||
+ clientRes.writableEnded
+ ) return;
+ if (failActiveResponse && upstreamResponseTerminal === null) {
+ failActiveResponse(err);
+ return;
+ }
logger.error?.('upstream request failed', {
reqId,
err: String(err),
method,
- path: upstreamPath,
+ path: upstreamPathname,
...(outboundProxy ? { viaProxy: outboundProxy.target.url } : {}),
});
- if (!clientRes.headersSent) {
- clientRes.writeHead(502, { 'content-type': 'application/json' });
- clientRes.end(JSON.stringify({ error: { type: 'proxy_error', message: `upstream unreachable: ${String(err)}` } }));
- } else {
- proxyDestroyedClient = true;
- clientRes.destroy(err);
- }
+ if (upstreamResponseTerminal === null) upstreamResponseTerminal = 'error';
+ const upstreamError = err instanceof Error ? err : new Error(String(err));
+ finishClientAfterUpstreamFailure(upstreamError, `upstream unreachable: ${String(err)}`);
});
upstreamReq.on('timeout', () => {
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 38d585d365..1036e6746b 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -31,6 +31,11 @@ export const DL_UNSUBSCRIBE_CHANNEL = 'device-link:unsubscribe';
/**
* cindy_helper 跨设备历史读取。被控端只接受单 session 的结构化只读查询,
* 并复用本机 history reader 的过滤、排序与游标语义。
+ *
+ * 响应除分页结果外附带可选 `terminal` 字段(会话尾部终态安全标记,
+ * { status:'error', createdAt? } 或 null):被控端与页面读取在同一次
+ * handler 调用内计算,保证标记与消息快照来自同一数据库时刻;错误正文
+ * 不出被控端。老被控端响应无此字段 → 控制端按无终态降级。
*/
export const DL_HISTORY_MESSAGES_CHANNEL = 'local-db:history:messages';