Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
/**
* 空洞补齐在会话屏幕上的接线守卫。
*
* 补齐算法本身在 `historyWindowGap.test.ts` 有行为测试;这里锁住屏幕侧那些"删掉也照样跑、但会
* 悄悄踩坑"的前置条件。#1210 的三轮 review 全部集中在这一层,所以先把不变量写清,再逐条对着断言
* ——每条不变量在代码里只允许有**一个**判据,所有对称路径复用它:
*
* 1. **一轮补齐的身份是单调的**:每次启动分配只增不减的 `runSeq`;"是否已被取代"、飞行标记的
* 清除、结论的写入,全都对着 seq 比。凡是"当前状态是否仍等于启动时状态"的判据都不可靠 ——
* 会话 id 会摆回来(A 在飞 → 切到 B → 快速切回 A),那种判据会把取消**撤销**掉,于是同一会话
* 并发翻页、旧轮收尾还误清新轮的标记,越滚越多。
* 2. **同一会话同一时刻最多一轮在飞**:互斥按 `inFlight.sid === sessionId`;别的会话残留的那一轮
* 不连坐当前会话(它自己会在下一次 isCancelled 上收手)。
* 3. **同步门槛按 session + 连接代判定**:屏实例会被原地复用,屏幕级 `lastSyncedAt` 在切会话后
* 仍是上一个会话的非空值,补齐会基于旧缓存快照动手。
* 4. **每个结局有独立的遗忘条件与预算归属**:contiguous(事实,永久跳过,不占翻页额度)/
* backfilled(真翻过页,占翻页额度)/ failed(绑 connectionEpoch,重连后可重试)/ cancelled(不记)。
* 5. **两道预算闸**:考察总次数(防海量正常停顿打出上百次探测)、翻页段数(防一路翻整场历史)。
* 6. **补齐永不写用户可见的加载态或错误**:它是静默自愈,失败由渲染层的空洞守卫兜底。
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import ts from 'typescript';
import { describe, expect, it } from 'vitest';
function readSource(...segments: string[]): string {
return readFileSync(resolve(process.cwd(), ...segments), 'utf8').replaceAll('\r\n', '\n');
}
describe('history window backfill wiring', () => {
const source = readSource('app/sessions/[sessionId].tsx');
it('不变量 1:一轮的身份是单调 seq,取消不可撤销', () => {
expect(source).toContain('const runSeq = backfillRunSeqRef.current + 1;');
expect(source).toContain('backfillLatestRunSeqRef.current = runSeq;');
// 取消判据对着 seq 比,不是"当前会话 id 是否仍等于启动时的"——后者会随切回来而摆回。
expect(source).toContain('isCancelled: () => backfillLatestRunSeqRef.current !== runSeq');
// 结论写入同样要求"我还是最新那一轮"。
expect(source).toMatch(
/if \(\s*backfillLatestRunSeqRef\.current !== runSeq\s*\|\| !remoteSessionStore\.isSessionMessageAuthorityCurrent\(messageAuthority\)\s*\) return;/,
);
// 收尾按 seq 精确清标记:按 sid 比会把切回同一会话后新起那一轮的标记误清。
expect(source).toContain('setBackfillInFlightRun((current) => (current?.seq === runSeq ? null : current));');
// 作废收敛成一个函数,三个入口共用(单向,不启动新轮):
expect(source).toContain('const abandonInFlightBackfill = useCallback(() => {');
expect(source).toContain('backfillRunSeqRef.current += 1;');
// ①切会话 ②换连接代 —— 被动 effect 足够
expect(source).toContain('}, [abandonInFlightBackfill, sessionId, connectionEpoch]);');
// ③手动「加载更早」—— 必须在**同步路径**里作废:effect 是被动的,而 loadEarlierMessages 在
// setLoadingEarlier(true) 之后同步就发请求,自动补齐可能在 effect 跑之前返回并继续下一页,
// 两条分页流程短暂并发(#1210 review)。
const manualEntry = source.slice(
source.indexOf('const loadEarlierMessages = useCallback'),
source.indexOf('setLoadingEarlier(true);', source.indexOf('const loadEarlierMessages = useCallback')),
);
expect(manualEntry).toContain('abandonInFlightBackfill();');
// 已退役的可摆动判据不得回归。
expect(source).not.toContain('backfillSessionRef');
expect(source).not.toContain('backfillInFlightRef');
});
it('不变量 2:互斥只挡同一会话,且飞行标记是可观察 state', () => {
expect(source).toContain('if (loading || loadingEarlier || backfillInFlightRun?.sid === sessionId) return;');
expect(source).toContain('const [backfillInFlightRun, setBackfillInFlightRun] = useState<{ sid: string; seq: number } | null>(null);');
});
it('不变量 3:同步门槛按 session + 连接代,不用屏幕级 lastSyncedAt', () => {
expect(source).toContain('const SESSION_READ_ACK_DWELL_MS = 200;');
expect(source).toContain('if (readAckSyncedKey !== `${sessionId}:${connectionEpoch}`) return;');
expect(source).not.toContain('|| lastSyncedAt === null) return;');
});
it('不变量 4:结局分三类,失败绑连接代,cancelled 不记,跳过表取并集', () => {
expect(source).toContain("if (outcome === 'contiguous') state.contiguous.add(gapKey);");
expect(source).toContain("else if (outcome === 'failed') state.failed.add(gapKey);");
expect(source).toContain("else if (outcome !== 'cancelled') state.backfilled.add(gapKey);");
// 断线那次不得把空洞永久钉死:换连接代只清 failed,重连后同一处可以再试。
expect(source).toContain('gapState.failed.clear();');
// 换会话时整体重置,否则上个会话的已考察集合会压住新会话的补齐。
expect(source).toContain('existingState?.sid === sessionId');
expect(source).toContain('state.sid !== sessionIdAtStart || state.epoch !== epochAtStart');
expect(source).toContain('findHistoryWindowGap(latestMessagesRef.current, consideredKeys)');
expect(source).toContain('...gapState.contiguous,');
expect(source).toContain('...gapState.backfilled,');
expect(source).toContain('...gapState.failed,');
});
it('不变量 5:两道预算闸都在,且额度只算翻过页的', () => {
expect(source).toContain('if (gapState.backfilled.size >= HISTORY_BACKFILL_MAX_GAPS_PER_VISIT) return;');
expect(source).toContain('if (consideredKeys.size >= HISTORY_GAP_MAX_CONSIDERED_PER_VISIT) return;');
// 硬编码的 3 不得回归:两道闸的语义与理由写在常量注释里。
expect(source).not.toContain('.backfilled.size >= 3');
});
it('不变量 6:补齐不写 error / loadingEarlier,锚点行消失即收手', () => {
// guard: #1210 的静默补齐契约。按实际调用所属的 effect 定界,不能用下一个
// 功能的声明作终点;创建追问插在两者之间时,其正常报错曾被误判为补齐报错。
const tree = ts.createSourceFile('session.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const effects: string[] = [];
const visit = (node: ts.Node) => {
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)
&& node.expression.text === 'backfillHistoryWindowGap') {
let effect: ts.Node | undefined = node.parent;
while (effect && !(ts.isCallExpression(effect) && ts.isIdentifier(effect.expression)
&& effect.expression.text === 'useEffect')) effect = effect.parent;
expect(effect, '补齐调用必须位于受守卫保护的 effect 中').toBeDefined();
effects.push(effect!.getText(tree));
}
ts.forEachChild(node, visit);
};
visit(tree);
expect(effects).toHaveLength(1);
const effectSource = effects[0];
expect(effectSource).toContain('.some((row) => row.id === gap.newerId)');
expect(effectSource).not.toContain('setError(');
expect(effectSource).not.toContain('setLoadingEarlier(');
});
it('探测页不沿用默认降级阶梯(第一枪就满页则探测白花),翻页页保留降级重试', () => {
expect(source).toContain('limit === HISTORY_GAP_PROBE_LIMIT ? [HISTORY_GAP_PROBE_LIMIT] : undefined,');
});
});
/**
* 实时流「生效 / 中断」通知的接线守卫。
*
* 不变量:**store 只在该会话的实时行确实会送到本端时,才允许 push 续推覆盖区间的上界**(见
* remoteSessionStore 的 `sessionWindowCoverage.liveTailTrusted`;行为测试在
* `remoteSessionStore.test.ts`)。于是两侧都要接线:订阅被远端 ACK(生效)一处、断流三处。漏掉任何
* 一处都会让窗口凭空背书出一段没收到的历史,而这种孤岛在半小时内产生时连自动探测都发现不了
* (#1210 review)。
*/
describe('live stream interruption wiring', () => {
const source = readSource('src/device-link/DeviceLinkContext.tsx');
it('订阅被远端 ACK:按真正记进 ACK 表的 topic 生效', () => {
const sendSubscribe = source.slice(
source.indexOf('const sendTrackedSubscribe = useCallback'),
source.indexOf('const probeUnresponsiveDevice'),
);
// 传的是 markHeldRemoteTopicsSubscribed 的返回值(仍被持有的那些),不是原始 toSend ——
// 中途被释放的 topic 不算订阅生效。
expect(sendSubscribe).toMatch(/const held = markHeldRemoteTopicsSubscribed\(remoteSubscribedTopicsRef\.current, registryRef\.current, deviceId, toSend\);\s*noteSessionLiveStreamsAcked\(held\);/);
expect(sendSubscribe).toContain("if (held.length > 0) record?.('subscription', 'applied', held.length)");
// scope 在 ensureOnline 等待期间变化时,已释放 topic 不能迟到发到主机;仍被其它 owner
// 持有的 topic 必须重新评估,不能和已释放 topic 一起饿死。
expect(sendSubscribe).toContain('.filter((topic) => registryRef.current.hasTopic(deviceId, topic))');
expect(sendSubscribe).toContain('toSend.every((topic) => registryRef.current.hasTopic(deviceId, topic))');
// The production loop is behavior-tested in subscriptionAcknowledgements.test.ts.
expect(sendSubscribe).toContain('await confirmTrackedSubscription({');
// 反向竞态同样要守住:快速释放后又切回时,旧 unsubscribe 在真正发帧前必须
// 剔除已经重新被 owner 持有的 topic,不能落在新 subscribe 后把实时流再关掉。
expect(source).toContain('(topic) => presenceAvailableByDeviceRef.current.get(deviceId) !== false && !registryRef.current.hasTopic(deviceId, topic)');
expect(source).toMatch(
/const toSend = shouldSendTopic \? topics\.filter\(shouldSendTopic\) : topics;[\s\S]*client\.invoke\(deviceId, \{\s*channel: DL_UNSUBSCRIBE_CHANNEL,\s*args: \[\{ topics: toSend \}\]/,
);
});
it('socket 掉线:整体失效(影响所有订阅)', () => {
const offlineStart = source.indexOf("if (next !== 'online') {");
const offlineEnd = source.indexOf('// presence 是当前在线控制端收到的 delta', offlineStart);
expect(offlineStart).toBeGreaterThan(0);
expect(offlineEnd).toBeGreaterThan(offlineStart);
const offlineBranch = source.slice(offlineStart, offlineEnd);
expect(offlineBranch).toContain('remoteSessionStore.noteLiveStreamInterrupted();');
});
it('peer ACK reset:无 durable owner 时仍保留独立 forced-open 恢复意图', () => {
expect(source).toContain('const forcedPeerRecoveryIntentRef = useRef(new PeerRecoveryOpenIntentRegistry());');
expect(source).toMatch(
/onPeerTransportReset[\s\S]*requestForcedPeerRecovery\(client, deviceId\)[\s\S]*rehydrate\(deviceId\)/,
);
expect(source).toMatch(/const rehydrate = \(deviceId\?: string\) => \{\s*catalogRefresh.wake\(deviceId\);\s*return rehydrateWithClient\(client, deviceId\);/);
expect(source).toContain('resolvePeerRecoveryPlan(');
expect(source).toContain('for (const deviceId of forcedPeerRecoveryIntentRef.current.deviceIds())');
expect(source).toContain('forcedPeerRecoveryIntentRef.current.complete(targetDeviceId, forcedGeneration)');
expect(source).toContain('client.hasPendingRequestsTo(deviceId)');
expect(source).toContain('!client.isOutboundExplicitlyClosed(deviceId)');
});
it('退后台释放 session 订阅:按被释放的会话失效', () => {
const release = source.slice(
source.indexOf('const releaseHeavyTopics = ()'),
source.indexOf('return releases;'),
);
expect(release).toContain('noteSessionLiveStreamsInterrupted(heavy);');
});
it('离开会话取消订阅:按被释放的会话失效', () => {
const unsubscribe = source.slice(
source.indexOf('const unsubscribe = useCallback'),
source.indexOf('const value = useMemo'),
);
expect(unsubscribe).toContain('noteSessionLiveStreamsInterrupted(toSend);');
});
});
// guard: Persistent data boundary: evicting a render cache must never delete the offline history.
describe("mobileSessionMessageCache.test.ts call-site contracts", () => {
it('does not treat an empty in-memory render snapshot as a cache deletion', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/remoteSessionStore.ts'), 'utf8');
expect(source).toContain('空内存可能只是 regular LRU 淘汰');
expect(source).toContain('if (messages.length === 0) return;');
expect(source).toContain("if (retentionForSession(sessionId) === 'schedule')");
});
});
// guard: remote-and-mobile-adaptation.md: stale session identity, loading cleanup, and retry generations cross the page/coordinator boundary.
describe("remoteSyncTask.test.ts call-site contracts", () => {
function readSessionScreenSource(): string {
return readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8').replace(/\r\n/g, '\n');
}
it('clears loading when a queued sync is blocked for a newly-created session', () => {
const source = readSessionScreenSource();
expect(source).toContain(
'if (shouldBlockSessionSync(sessionId)) {\n if (!syncRun.isStale()) setLoading(false);\n return;\n }',
);
});
it('resets loading when the reused screen switches sessions', () => {
const source = readSessionScreenSource();
expect(source).toContain(
'setRewindState({ kind: \'idle\' });\n setMessageActionBusy(null);\n setLoading(false);',
);
});
it('uses the force-reopen callback for subscription and snapshot retries', () => {
const source = readSessionScreenSource();
expect(source).toContain(
'reopenLink: () => syncReopenCoordinator.reopenAfter(subscriptionAttemptVersion)',
);
expect(source).toContain(
'await syncReopenCoordinator.reopenAfter(failedAtVersion);',
);
expect(source).toContain(
'const syncReopenCoordinator = createRemoteSyncReopenCoordinator(',
);
expect(source).not.toContain(
'reopenLink: async () => {\n await openLink(deviceId);\n }',
);
});
it('applies coordinator context and task changes after render commits', () => {
const source = readFileSync(
resolve(process.cwd(), 'src/device-link/remoteSyncTask.ts'),
'utf8',
).replace(/\r\n/g, '\n');
expect(source).toContain(
'useLayoutEffect(() => {\n taskRef.current = task;\n coordinatorRef.current?.setContext(contextKey);\n }, [contextKey, task]);',
);
expect(source).not.toContain(
' taskRef.current = task;\n const coordinatorRef =',
);
expect(source).not.toContain('coordinatorRef.current.setContext(contextKey);');
});
});