|
|
@@ -1,7 +1,15 @@
|
|
|
/** 首屏加载条数:只渲染最近一屏,其余上滚再取(用户要求,避免一次性加载全部) */
|
|
|
const INITIAL_PAGE = 30;
|
|
|
+/**
|
|
|
+ * 未认领线程根的实时消息,在本会话闲置超过这个时长后一律不收(2026-11-16)。
|
|
|
+ *
|
|
|
+ * 背景见 `belongsToSession()` 的 `live` 分支:要挡的是「切到别的会话后,
|
|
|
+ * 原会话的线程根还在往外冒事件」。取 30 分钟是因为真实对话中不会闲置这么久
|
|
|
+ * 却突然收到同一次对话的产出;而切会话后的延迟投递通常在几秒到几分钟内。
|
|
|
+ */
|
|
|
+const IDLE_GUARD_MS = 30 * 60 * 1000;
|
|
|
|
|
|
-import { computed, effect, inject, Injectable, signal, untracked } from '@angular/core';
|
|
|
+import { computed, effect, inject, Injectable, signal, untracked, WritableSignal } from '@angular/core';
|
|
|
import { FmodeApi } from './api/fmode-api';
|
|
|
import {
|
|
|
Agent,
|
|
|
@@ -168,7 +176,12 @@ export class ChatService {
|
|
|
* 🔴 用户要求:**先选文件、点发送时才一起发出去**,而不是选完立刻上传。
|
|
|
* 所以这里只持有 File 对象,不上传、不发消息 —— 发送时才落地。
|
|
|
*/
|
|
|
- private readonly _pendingFiles = signal<PendingFile[]>([]);
|
|
|
+ private readonly _pendingFileStore = signal<ReadonlyMap<string, WritableSignal<PendingFile[]>>>(new Map());
|
|
|
+ private readonly _pendingFiles = computed(
|
|
|
+ () => this._pendingFileStore().get(this.pendingFileKey())?.() ?? [],
|
|
|
+ );
|
|
|
+ private _pendingFileEpoch = 0;
|
|
|
+ private readonly activeSubmissions = new WeakMap<WritableSignal<PendingFile[]>, Set<string>>();
|
|
|
/**
|
|
|
* 上传总进度 0-100(2026-11-11 改为**按字节加权实时计算**)。
|
|
|
*
|
|
|
@@ -318,7 +331,7 @@ export class ChatService {
|
|
|
readonly sending = this._sending.asReadonly();
|
|
|
readonly uploading = this._uploading.asReadonly();
|
|
|
/** 待发送附件(界面据此渲染缩略条与移除按钮) */
|
|
|
- readonly pendingFiles = this._pendingFiles.asReadonly();
|
|
|
+ readonly pendingFiles = this._pendingFiles;
|
|
|
readonly uploadPct = this._uploadPct.asReadonly();
|
|
|
/** 整批上传阶段(输入框下方那条进度条据此切文案,2026-11-11) */
|
|
|
readonly uploadPhase = this._uploadPhase.asReadonly();
|
|
|
@@ -1130,6 +1143,7 @@ export class ChatService {
|
|
|
*/
|
|
|
|
|
|
// 切到这条新会话(左侧随之高亮,见 session-tree 的 activeId)
|
|
|
+ if (!this._sessionId()) this.adoptPendingFiles(this.pendingFileKey(), s.id);
|
|
|
this._sessionId.set(s.id);
|
|
|
|
|
|
/*
|
|
|
@@ -1868,6 +1882,12 @@ export class ChatService {
|
|
|
*/
|
|
|
close(): void {
|
|
|
this.seq++;
|
|
|
+ this._pendingFileEpoch++;
|
|
|
+ for (const bucket of this._pendingFileStore().values()) this.clearPendingFileBucket(bucket);
|
|
|
+ this._pendingFileStore.set(new Map());
|
|
|
+ this._uploading.set(false);
|
|
|
+ this._uploadPct.set(0);
|
|
|
+ this._uploadPhase.set('idle');
|
|
|
this.teardownSubscriptions();
|
|
|
this.provision = null;
|
|
|
this.roomId = null;
|
|
|
@@ -2091,7 +2111,17 @@ export class ChatService {
|
|
|
* 用户知情并接受,仅在发送按钮上由 `sendHint()` 提示。
|
|
|
*/
|
|
|
async sendText(text: string): Promise<void> {
|
|
|
- await this.sendTextInternal(text);
|
|
|
+ const bucket = this.pendingFileBucket();
|
|
|
+ const submissionKey = JSON.stringify([text.trim(), bucket().map((file) => file.id)]);
|
|
|
+ const active = this.activeSubmissions.get(bucket) ?? new Set<string>();
|
|
|
+ if (active.has(submissionKey)) return;
|
|
|
+ this.activeSubmissions.set(bucket, active);
|
|
|
+ active.add(submissionKey);
|
|
|
+ try {
|
|
|
+ await this.sendTextInternal(text);
|
|
|
+ } finally {
|
|
|
+ active.delete(submissionKey);
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
private async sendTextInternal(text: string): Promise<void> {
|
|
|
@@ -2202,6 +2232,7 @@ export class ChatService {
|
|
|
* 否则用户「打一半 → 会话建好」时字会消失(2026-11-14)。
|
|
|
*/
|
|
|
this.adoptDraft(this._draftKey(), created.id);
|
|
|
+ this.adoptPendingFiles(this.pendingFileKey(), created.id);
|
|
|
this._sessionId.set(created.id);
|
|
|
/*
|
|
|
* 🔴 必须同时把状态从 empty 切到 ready(2026-11-01 修复)。
|
|
|
@@ -2277,6 +2308,12 @@ export class ChatService {
|
|
|
*/
|
|
|
const currentSessionId = this._sessionId();
|
|
|
if (currentSessionId) this.pulse.noteSessionUserAction(currentSessionId);
|
|
|
+ const pendingUpload = {
|
|
|
+ bucket: this.pendingFileBucket(),
|
|
|
+ roomId: this.roomId,
|
|
|
+ sessionId: currentSessionId,
|
|
|
+ epoch: this._pendingFileEpoch,
|
|
|
+ };
|
|
|
|
|
|
try {
|
|
|
/*
|
|
|
@@ -2322,15 +2359,17 @@ export class ChatService {
|
|
|
* 它会回「没看到附件」—— 用户白等一轮,会话里还多出半截对话。
|
|
|
* 与其留下脏状态,不如**当场失败、当场清干净**。
|
|
|
*/
|
|
|
- if (this._pendingFiles().length > 0) {
|
|
|
- const { fail } = await this.uploadPending(conversationId);
|
|
|
+ if (pendingUpload.epoch !== this._pendingFileEpoch) return;
|
|
|
+ if (pendingUpload.bucket().length > 0) {
|
|
|
+ const { fail } = await this.uploadPending(conversationId, pendingUpload);
|
|
|
+ if (pendingUpload.epoch !== this._pendingFileEpoch) return;
|
|
|
if (fail > 0) {
|
|
|
/*
|
|
|
* 逐条失败原因已由 uploadPending 写入 `_error` / 全局提示;
|
|
|
* 这里负责**回滚**:撤掉刚插入的本条消息、清空草稿与暂存附件,
|
|
|
* 让页面回到「发送前」的状态,用户可以直接重试。
|
|
|
*/
|
|
|
- this.rollbackSend(msg.id);
|
|
|
+ this.rollbackSend(msg.id, pendingUpload.bucket);
|
|
|
this._error.set(
|
|
|
this._error() ?? `${fail} 个附件未上传到云盘,本条消息未发送`,
|
|
|
);
|
|
|
@@ -2568,7 +2607,7 @@ export class ChatService {
|
|
|
this._error.set(rejected.map(oversizeMessage).join(';'));
|
|
|
}
|
|
|
if (list.length === 0) return;
|
|
|
- this._pendingFiles.update((cur) => [
|
|
|
+ this.pendingFileBucket().update((cur) => [
|
|
|
...cur,
|
|
|
...list.map((file) => ({
|
|
|
id: `pf-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
|
|
|
@@ -2582,7 +2621,7 @@ export class ChatService {
|
|
|
|
|
|
/** 移除一个待发附件(同时释放预览地址) */
|
|
|
unstageFile(id: string): void {
|
|
|
- this._pendingFiles.update((cur) => {
|
|
|
+ this.pendingFileBucket().update((cur) => {
|
|
|
const victim = cur.find((f) => f.id === id);
|
|
|
if (victim?.previewUrl) URL.revokeObjectURL(victim.previewUrl);
|
|
|
return cur.filter((f) => f.id !== id);
|
|
|
@@ -2591,10 +2630,41 @@ export class ChatService {
|
|
|
|
|
|
/** 清空待发附件(同时释放预览地址) */
|
|
|
clearPendingFiles(): void {
|
|
|
- for (const f of this._pendingFiles()) {
|
|
|
+ this.clearPendingFileBucket(this.pendingFileBucket());
|
|
|
+ }
|
|
|
+
|
|
|
+ private pendingFileKey(): string {
|
|
|
+ return this._sessionId() || (this._agentId() ? `agent:${this._agentId()}` : '');
|
|
|
+ }
|
|
|
+
|
|
|
+ private pendingFileBucket(): WritableSignal<PendingFile[]> {
|
|
|
+ const key = this.pendingFileKey();
|
|
|
+ const existing = this._pendingFileStore().get(key);
|
|
|
+ if (existing) return existing;
|
|
|
+ const bucket = signal<PendingFile[]>([]);
|
|
|
+ this._pendingFileStore.update((store) => new Map(store).set(key, bucket));
|
|
|
+ return bucket;
|
|
|
+ }
|
|
|
+
|
|
|
+ private adoptPendingFiles(fromKey: string, toKey: string): void {
|
|
|
+ if (!toKey || fromKey === toKey) return;
|
|
|
+ const bucket = this._pendingFileStore().get(fromKey);
|
|
|
+ if (!bucket) return;
|
|
|
+ const destination = this._pendingFileStore().get(toKey);
|
|
|
+ if (destination) bucket.update((files) => [...destination(), ...files]);
|
|
|
+ this._pendingFileStore.update((store) => {
|
|
|
+ const next = new Map(store);
|
|
|
+ next.delete(fromKey);
|
|
|
+ next.set(toKey, bucket);
|
|
|
+ return next;
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ private clearPendingFileBucket(bucket: WritableSignal<PendingFile[]>): void {
|
|
|
+ for (const f of bucket()) {
|
|
|
if (f.previewUrl) URL.revokeObjectURL(f.previewUrl);
|
|
|
}
|
|
|
- this._pendingFiles.set([]);
|
|
|
+ bucket.set([]);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -2603,12 +2673,13 @@ export class ChatService {
|
|
|
* 进度与阶段**都从各文件自己的状态派生**,不再手动 set 一个总数 ——
|
|
|
* 这样多文件并发/串行、某个文件失败时,总体进度都是自洽的。
|
|
|
*/
|
|
|
- private setFileProgress(id: string, progress: Omit<FileProgress, 'id'>): void {
|
|
|
+ private setFileProgress(bucket: WritableSignal<PendingFile[]>, id: string, progress: Omit<FileProgress, 'id'>): void {
|
|
|
const next: FileProgress = { id, ...progress };
|
|
|
- this._pendingFiles.update((cur) =>
|
|
|
+ bucket.update((cur) =>
|
|
|
cur.map((f) => (f.id === id ? { ...f, progress: next } : f)),
|
|
|
);
|
|
|
- const items = this._pendingFiles();
|
|
|
+ if (this._pendingFileStore().get(this.pendingFileKey()) !== bucket) return;
|
|
|
+ const items = bucket();
|
|
|
this._uploadPct.set(overallPct(items.map((f) => ({ progress: f.progress, size: f.file.size }))));
|
|
|
this._uploadPhase.set(batchPhase(items.map((f) => ({ progress: f.progress }))));
|
|
|
}
|
|
|
@@ -2618,9 +2689,16 @@ export class ChatService {
|
|
|
*
|
|
|
* @returns 每个附件是否成功
|
|
|
*/
|
|
|
- private async uploadPending(conversationId: string): Promise<{ ok: number; fail: number }> {
|
|
|
- const pending = this._pendingFiles();
|
|
|
- if (pending.length === 0) return { ok: 0, fail: 0 };
|
|
|
+ private async uploadPending(conversationId: string, context: {
|
|
|
+ bucket: WritableSignal<PendingFile[]>;
|
|
|
+ roomId: string | null;
|
|
|
+ sessionId: string | null;
|
|
|
+ epoch: number;
|
|
|
+ }): Promise<{ ok: number; fail: number }> {
|
|
|
+ const { bucket, roomId, sessionId: sid, epoch } = context;
|
|
|
+ const pending = bucket();
|
|
|
+ if (pending.length === 0 || epoch !== this._pendingFileEpoch) return { ok: 0, fail: 0 };
|
|
|
+ const ledgerRoot = sid ?? this.ensureSessionForSend()?.id;
|
|
|
|
|
|
this._uploading.set(true);
|
|
|
this._uploadPct.set(0);
|
|
|
@@ -2658,8 +2736,7 @@ export class ChatService {
|
|
|
* 回退:`localStorage.fmode.sendMode='mxc'` 即恢复旧双写。
|
|
|
*/
|
|
|
const mimeType = file.type || 'application/octet-stream';
|
|
|
- if (!this.roomId) throw new Error('会话未就绪');
|
|
|
- const sid = this._sessionId();
|
|
|
+ if (!roomId) throw new Error('会话未就绪');
|
|
|
|
|
|
/*
|
|
|
* ① 云盘:失败即中止本文件(不发送)。传 onProgress 拿**真实字节进度**(2026-11-11)
|
|
|
@@ -2670,17 +2747,18 @@ export class ChatService {
|
|
|
let cloudUrl: string;
|
|
|
let cloudKey: string;
|
|
|
let registered: boolean;
|
|
|
- const cached = this._pendingFiles().find((p) => p.id === pending[i].id)?.uploaded;
|
|
|
+ const cached = bucket().find((p) => p.id === pending[i].id)?.uploaded;
|
|
|
if (cached) {
|
|
|
cloudUrl = cached.url;
|
|
|
cloudKey = cached.key;
|
|
|
registered = cached.registered;
|
|
|
- this.setFileProgress(pending[i].id, { phase: 'uploading', pct: 100 });
|
|
|
+ this.setFileProgress(bucket, pending[i].id, { phase: 'uploading', pct: 100 });
|
|
|
} else {
|
|
|
- this.setFileProgress(pending[i].id, { phase: 'uploading', pct: 0 });
|
|
|
+ this.setFileProgress(bucket, pending[i].id, { phase: 'uploading', pct: 0 });
|
|
|
const up = await this.api.uploadFile(file, (pct) => {
|
|
|
- this.setFileProgress(pending[i].id, { phase: 'uploading', pct });
|
|
|
+ if (epoch === this._pendingFileEpoch) this.setFileProgress(bucket, pending[i].id, { phase: 'uploading', pct });
|
|
|
});
|
|
|
+ if (epoch !== this._pendingFileEpoch) return { ok, fail };
|
|
|
cloudUrl = up.publicUrl;
|
|
|
cloudKey = up.key;
|
|
|
registered = false;
|
|
|
@@ -2709,14 +2787,13 @@ export class ChatService {
|
|
|
*
|
|
|
* 修法:先确保会话存在(与 `sendReal` 同一兜底),再登记。
|
|
|
*/
|
|
|
- const ledgerRoot = sid ?? this.ensureSessionForSend()?.id;
|
|
|
if (ledgerRoot && !registered) {
|
|
|
try {
|
|
|
- this.setFileProgress(pending[i].id, { phase: 'registering', pct: 100 });
|
|
|
+ this.setFileProgress(bucket, pending[i].id, { phase: 'registering', pct: 100 });
|
|
|
await this.api.registerFile({
|
|
|
threadRoot: ledgerRoot,
|
|
|
- agentId: this._agentId() ?? undefined,
|
|
|
- roomId: this.roomId,
|
|
|
+ agentId: conversationId,
|
|
|
+ roomId,
|
|
|
name: file.name,
|
|
|
url: cloudUrl,
|
|
|
key: cloudKey,
|
|
|
@@ -2726,30 +2803,33 @@ export class ChatService {
|
|
|
});
|
|
|
registered = true;
|
|
|
} catch (e) {
|
|
|
+ if (epoch !== this._pendingFileEpoch) return { ok, fail };
|
|
|
this._error.set(
|
|
|
`「${file.name}」已存入云盘,但未记入文件列表:${e instanceof Error ? e.message : '登记失败'}`,
|
|
|
);
|
|
|
}
|
|
|
}
|
|
|
+ if (epoch !== this._pendingFileEpoch) return { ok, fail };
|
|
|
/*
|
|
|
* 先把「已上云」记到暂存项上,再发事件 —— 若下一步失败,
|
|
|
* 下一步重试就只重发事件(评审 S3)。
|
|
|
*/
|
|
|
- this._pendingFiles.update((cur) =>
|
|
|
+ bucket.update((cur) =>
|
|
|
cur.map((p) => (p.id === pending[i].id ? { ...p, uploaded: { url: cloudUrl, key: cloudKey, registered } } : p)),
|
|
|
);
|
|
|
|
|
|
/* ② Matrix:把云盘地址发给容器(2026-11-13 起不再传文件本体) */
|
|
|
- this.setFileProgress(pending[i].id, { phase: 'sending', pct: 100 });
|
|
|
+ this.setFileProgress(bucket, pending[i].id, { phase: 'sending', pct: 100 });
|
|
|
await this.sendCloudFile(
|
|
|
- this.roomId,
|
|
|
+ roomId,
|
|
|
file,
|
|
|
cloudUrl,
|
|
|
{ name: file.name, size: file.size, mimeType },
|
|
|
/* 🔴 与台账登记用**同一个根**,否则容器回的归属和台账对不上(2026-11-13) */
|
|
|
ledgerRoot ?? undefined,
|
|
|
);
|
|
|
- this.setFileProgress(pending[i].id, { phase: 'done', pct: 100 });
|
|
|
+ if (epoch !== this._pendingFileEpoch) return { ok, fail };
|
|
|
+ this.setFileProgress(bucket, pending[i].id, { phase: 'done', pct: 100 });
|
|
|
/*
|
|
|
* 云盘地址记进 `_cloudUrls`:**只服务于 `'mxc'` 回退模式**下的老消息
|
|
|
* (事件里没带 `com.fmode.cloud_url` 的那种)。`'url'` 模式下事件自带地址,
|
|
|
@@ -2760,6 +2840,11 @@ export class ChatService {
|
|
|
*/
|
|
|
this._cloudUrls.set(this.cloudKeyOf(file.name, file.size), cloudUrl);
|
|
|
|
|
|
+ if (this._pendingFileStore().get(this.pendingFileKey()) !== bucket) {
|
|
|
+ ok++;
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
// 本地预览用对象地址;Matrix 的 mxc 要等回读后才能转 http
|
|
|
const displayUrl = URL.createObjectURL(file);
|
|
|
const card: FileCard = {
|
|
|
@@ -2792,6 +2877,7 @@ export class ChatService {
|
|
|
]);
|
|
|
ok++;
|
|
|
} catch (e) {
|
|
|
+ if (epoch !== this._pendingFileEpoch) return { ok, fail };
|
|
|
fail++;
|
|
|
failedIds.add(pending[i].id);
|
|
|
const why = e instanceof Error ? e.message : '上传失败';
|
|
|
@@ -2808,7 +2894,7 @@ export class ChatService {
|
|
|
`「${file.name}」未能上传到云盘`,
|
|
|
`${why}。附件只走云盘直链,不会退回其它通道 —— 本条消息未发送。`,
|
|
|
);
|
|
|
- this.setFileProgress(pending[i].id, {
|
|
|
+ this.setFileProgress(bucket, pending[i].id, {
|
|
|
phase: 'failed',
|
|
|
pct: 0,
|
|
|
error: why,
|
|
|
@@ -2816,9 +2902,11 @@ export class ChatService {
|
|
|
}
|
|
|
}
|
|
|
} finally {
|
|
|
- this._uploading.set(false);
|
|
|
- this._uploadPct.set(0);
|
|
|
- this._uploadPhase.set('idle');
|
|
|
+ if (epoch === this._pendingFileEpoch) {
|
|
|
+ this._uploading.set(false);
|
|
|
+ this._uploadPct.set(0);
|
|
|
+ this._uploadPhase.set('idle');
|
|
|
+ }
|
|
|
/*
|
|
|
* 🔴 按 id 精确保留失败项(2026-11-03 修复)。
|
|
|
*
|
|
|
@@ -2828,7 +2916,7 @@ export class ChatService {
|
|
|
*
|
|
|
* 同时要 revoke 被移除项的 previewUrl,避免对象地址泄漏。
|
|
|
*/
|
|
|
- this._pendingFiles.update((cur) => {
|
|
|
+ bucket.update((cur) => {
|
|
|
const remain = cur.filter((f) => failedIds.has(f.id));
|
|
|
for (const f of cur) {
|
|
|
if (!failedIds.has(f.id) && f.previewUrl) URL.revokeObjectURL(f.previewUrl);
|
|
|
@@ -3048,6 +3136,25 @@ export class ChatService {
|
|
|
*/
|
|
|
private async sendReal(text: string, localId?: string): Promise<void> {
|
|
|
if (!this.roomId) throw new Error('会话未就绪,请稍后重试');
|
|
|
+ /*
|
|
|
+ * 🔴 断网时必须**主动判定失败**(2026-11-16 真机实测补)。
|
|
|
+ *
|
|
|
+ * ## 为什么不能只靠 `mx.sendText()` 抛错
|
|
|
+ *
|
|
|
+ * Matrix SDK 的 `client.sendEvent()` 在**离线时会把事件塞进本地队列并正常 resolve**。
|
|
|
+ * 于是 `sendTextInternal` 的 catch 不触发、`markFailed` 不被调用,
|
|
|
+ * 界面那条消息就跟正常发送的一模一样:只显示时间,无失败标识、无重试。
|
|
|
+ *
|
|
|
+ * 真机实测(小米 M2102K1AC / Android 14,飞行模式下发送):
|
|
|
+ * 气泡正常上屏 → 输入框清空 → 20 秒后仍只显示时间 → 与正常消息 DOM 结构完全相同。
|
|
|
+ * 用户会以为消息已经发出去了,实际可能永远停在队列里。
|
|
|
+ *
|
|
|
+ * 所以发送前先看连接状态:不在线就直接抛错,走既有的
|
|
|
+ * `catch → markFailed` 链路(UI 的失败态与重试按钮已就绪,见 m-msg.ts)。
|
|
|
+ */
|
|
|
+ if (this._connection() === 'disconnected') {
|
|
|
+ throw new Error('网络已断开,消息未发送');
|
|
|
+ }
|
|
|
let sid = this._sessionId();
|
|
|
if (!sid) {
|
|
|
/*
|
|
|
@@ -3117,6 +3224,7 @@ export class ChatService {
|
|
|
const recreated = this.sessions.create(roomId, agentId);
|
|
|
// 键变了 → 草稿跟着挪(2026-11-14),否则用户打了一半的字会消失
|
|
|
this.adoptDraft(this._draftKey(), recreated.id);
|
|
|
+ this.adoptPendingFiles(this.pendingFileKey(), recreated.id);
|
|
|
this._sessionId.set(recreated.id);
|
|
|
/*
|
|
|
* 🔴 换了会话标识,内存里属于旧会话的消息必须清掉(2026-11-09)。
|
|
|
@@ -3300,14 +3408,105 @@ export class ChatService {
|
|
|
*
|
|
|
* 现在:**历史回填**时容器线程根只归「已经认领过它」的会话 ——
|
|
|
* 新会话从没认领过任何根,自然什么都拿不到,符合「新建即空白」的预期。
|
|
|
- * **实时事件**(`live=true`)仍然接纳:那是容器刚刚发出的内容,
|
|
|
- * 一定是当前这次对话的产出(截图、交付物都在里面)。
|
|
|
+ *
|
|
|
+ * ## 🔴 2026-11-16 真机修复:实时事件也必须过 `ownedRoots` 这一关
|
|
|
+ *
|
|
|
+ * 原实现的 `live` 分支直接 `return !isAppSessionId(m.threadId)`,
|
|
|
+ * **跳过了归属校验** —— 只要线程根不是 App 造的,就归「当前打开的会话」。
|
|
|
+ *
|
|
|
+ * 用户实测反馈:「前一个会话输出的文件,后一个会话也会携带」。
|
|
|
+ * 根因就在这里:用户在会话 A 的时候,容器在 A 的线程根下产生了附件事件;
|
|
|
+ * 用户切到会话 B 后,**A 的线程根若还有新事件实时到达**(延迟投递、
|
|
|
+ * 容器补发、Matrix 重连补同步),B 会把它全部认领 ——
|
|
|
+ * 于是 A 的文件出现在 B 里。
|
|
|
+ *
|
|
|
+ * 向容器 `agent-node-lj-test` 核实(2026-11-16),容器原话:
|
|
|
+ * 「我发文件只针对本次请求里实际生成/引用的路径,不会自动把旧会话的
|
|
|
+ * 文件再发一遍。如果新会话里出现了旧文件,那是……App 端把历史消息
|
|
|
+ * 归到了当前会话。跨会话携带请在 App 端按 thread 根 + event_id 归属过滤。」
|
|
|
+ *
|
|
|
+ * 所以 `live` 降级为「**额外**放行条件」,而不是「**替代**归属校验」:
|
|
|
+ * · 历史回填 → 必须有 ownedRoots 认领(不变)
|
|
|
+ * · 实时事件 → 同样必须有 ownedRoots 认领;否则丢弃
|
|
|
+ *
|
|
|
+ * 那「容器刚开的新线程根」怎么办?`_ownedThreadRoots` 在
|
|
|
+ * `openReal` 时会从 timeline 重新计算,而 `isAwaitingReplyAfter`
|
|
|
+ * 那条房间级消息的路径仍会认领**正在等回复时的**无 thread 消息 ——
|
|
|
+ * 容器本轮的正常产出照样进得来。
|
|
|
+ *
|
|
|
+ * 代价(已知且可接受):极少数「容器在本会话首次开新线程根」的实时事件
|
|
|
+ * 可能延迟到下一次回填才出现,而不是实时冒出来。
|
|
|
*/
|
|
|
- if (live) return !isAppSessionId(m.threadId);
|
|
|
const roots = ownedRoots ?? this._ownedThreadRoots;
|
|
|
+ if (live) {
|
|
|
+ /*
|
|
|
+ * 已认领的根 → 一定是本会话的,直接放行(最快路径,也是常态)。
|
|
|
+ */
|
|
|
+ if (roots.has(m.threadId)) return true;
|
|
|
+ if (isAppSessionId(m.threadId)) return false;
|
|
|
+ /*
|
|
|
+ * 未认领的容器线程根,实时到达。
|
|
|
+ *
|
|
|
+ * ## 2026-11-16 真机修复(第二版)
|
|
|
+ *
|
|
|
+ * 用户实测反馈「前一个会话输出的文件,后一个会话也会携带」。
|
|
|
+ * 原实现这里的规则是 `return !isAppSessionId(m.threadId)` —— **无条件放行**,
|
|
|
+ * 于是切到会话 B 后,A 的线程根若有事件实时到达,B 会认领成自己的内容。
|
|
|
+ *
|
|
|
+ * ## 为什么第一版修得太狠(已回退)
|
|
|
+ *
|
|
|
+ * 第一版要求「本会话必须正在等回复」才放行,结果真机上
|
|
|
+ * **容器的正常回复整段消失**(会话里只剩用户消息)。
|
|
|
+ * 原因:容器的回复挂在它自己开的线程根下,而这个根不在 `ownedRoots` 里,
|
|
|
+ * 一旦用户消息发出到容器回复之间隔得久一点,回复就被挡掉了。
|
|
|
+ * 宁可少一点隔离,也不能丢消息。
|
|
|
+ *
|
|
|
+ * ## 现在的判据:**只挡「别的会话的根」**
|
|
|
+ *
|
|
|
+ * 容器在 DM 里开的线程根,本质是「本次对话的产出」。要区分它属于谁,
|
|
|
+ * 唯一的线索是**时间**:别的会话的旧线程根,其消息时间早于本会话开启时间。
|
|
|
+ *
|
|
|
+ * · 本会话**近期有活动**(发过消息 / 在等回复 / 刚收到过消息)→ 放行
|
|
|
+ * (这就是正常对话进行中的情况,容器产出必须能进来)
|
|
|
+ * · 本会话**长期闲置**,却来了个陌生根的消息 → 大概率是别处的旧事件
|
|
|
+ * (切换会话后的延迟投递 / Matrix 重连补同步),挡掉
|
|
|
+ *
|
|
|
+ * `IDLE_GUARD_MS` 取 30 分钟:真实对话中两次「活动」不会隔这么久,
|
|
|
+ * 而切到另一个会话后,A 的旧事件通常在几秒到几分钟内到达 —— 会被挡掉。
|
|
|
+ */
|
|
|
+ return !this.isIdleBeyond(IDLE_GUARD_MS);
|
|
|
+ }
|
|
|
return roots.has(m.threadId);
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 本会话是否已经「闲置」超过指定时长(2026-11-16)。
|
|
|
+ *
|
|
|
+ * 用于判断一条**未认领线程根**的实时消息该不该收:
|
|
|
+ * 会话正在活跃时,陌生根的消息大概率就是容器本轮的产出,应当收;
|
|
|
+ * 会话长期无动静却来了消息,大概率是别的会话的旧事件被延迟投递,应当挡。
|
|
|
+ *
|
|
|
+ * @returns true = 已闲置超过 `ms`(或会话里没有任何消息)
|
|
|
+ */
|
|
|
+ private isIdleBeyond(ms: number): boolean {
|
|
|
+ const list = this._messages();
|
|
|
+ /*
|
|
|
+ * 🔴 空会话**不算闲置**(2026-11-16)。
|
|
|
+ *
|
|
|
+ * 刚打开的会话、或用户刚进来还没发消息的会话,容器完全可能主动产出内容
|
|
|
+ * (它可能在处理上一轮的后台任务)。把空会话当成「闲置」会把这些产出挡掉,
|
|
|
+ * 真机实测就是「会话里什么都没有」。
|
|
|
+ */
|
|
|
+ if (list.length === 0) return false;
|
|
|
+ let last = 0;
|
|
|
+ for (const m of list) {
|
|
|
+ const t = Date.parse(m.ts) || 0;
|
|
|
+ if (t > last) last = t;
|
|
|
+ }
|
|
|
+ if (!last) return false;
|
|
|
+ return Date.now() - last > ms;
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 本会话是否「已发出消息、容器还没回」(2026-11-10,B)。
|
|
|
*
|
|
|
@@ -3880,7 +4079,7 @@ export class ChatService {
|
|
|
* 🔴 与 `markFailed` 的区别:那个把消息标红留着重试,
|
|
|
* 用于「已发出但回执失败」。这里连消息都没有,留着只剩困惑。
|
|
|
*/
|
|
|
- private rollbackSend(localId: string): void {
|
|
|
+ private rollbackSend(localId: string, pendingBucket: WritableSignal<PendingFile[]>): void {
|
|
|
const victim = this._messages().find((m) => m.id === localId);
|
|
|
this._messages.update((list) => list.filter((m) => m.id !== localId));
|
|
|
/* 文字回填:用户刚打的内容不能丢 */
|
|
|
@@ -3888,7 +4087,7 @@ export class ChatService {
|
|
|
// 2026-11-14:草稿已按会话分桶,回填写进**当前会话**这一桶
|
|
|
if (text && !this._draft().trim()) this.writeDraft(text);
|
|
|
/* 暂存附件清空(上传已失败,重新选比留着更有确定性) */
|
|
|
- this.clearPendingFiles();
|
|
|
+ this.clearPendingFileBucket(pendingBucket);
|
|
|
}
|
|
|
|
|
|
private markFailed(id: string, error: string): void {
|