chat.ts 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209
  1. import { UserNoticePipe } from '../../../components/feedback/user-notice.pipe';
  2. import {
  3. ChangeDetectionStrategy,
  4. Component,
  5. ElementRef,
  6. OnDestroy,
  7. computed,
  8. effect,
  9. inject,
  10. signal,
  11. untracked,
  12. viewChild,
  13. } from '@angular/core';
  14. import { ActivatedRoute, Router } from '@angular/router';
  15. import { MAppBarComponent } from '../../components/m-app-bar/m-app-bar';
  16. import { MDockComponent } from '../../components/m-dock/m-dock';
  17. import { MDrawerComponent } from '../../components/m-drawer/m-drawer';
  18. import { MNewChatSheetComponent } from '../../components/m-new-chat/m-new-chat';
  19. import { MProjectSwitcherComponent } from '../../components/m-project-switcher/m-project-switcher';
  20. import { TitleEditorComponent } from '../../components/m-title-editor/m-title-editor';
  21. import { MEmptyComponent } from '../../components/m-empty/m-empty';
  22. import { MMsgComponent } from '../../components/m-msg/m-msg';
  23. import { FilePreviewComponent } from '../../../components/preview/file-preview/file-preview';
  24. import { ImageLightboxComponent } from '../../../components/preview/image-lightbox/image-lightbox';
  25. import { previewKindOf } from '../../../components/preview/file-kind';
  26. import { LockScrollDirective } from '../../directives/lock-scroll.directive';
  27. import { BadgeTone, MBadgeComponent, TASK_TONE, TASK_STATUS_TEXT } from '../../components/m-badge/m-badge';
  28. import { ChatService } from '../../../core/chat.service';
  29. import { ShareReceiveService } from '../../../core/share-receive.service';
  30. import { PENDING_DRAFT_KEY } from '../home/home';
  31. import { LoopGuardService } from '../../../core/loop-guard.service';
  32. import { Agent, Deliverable, SemanticTone, Task } from '../../../core/api/models';
  33. import { ChatSessionService } from '../../../core/chat-session.service';
  34. import { TasksService } from '../../../core/tasks.service';
  35. import { fmtSize } from '../../../core/format';
  36. import { MobileChatViewService } from '../../../core/mobile-chat-view.service';
  37. import { DeliverablesService } from '../../../core/deliverables.service';
  38. import { AgentFileBindingService } from '../../../core/agent-file-binding.service';
  39. import { agentMessageFiles } from '../../../core/message-files';
  40. import { buildTurns, QUIET_MS } from '../../../core/turn-aggregator';
  41. import {
  42. Block,
  43. isToolActivityMessage,
  44. toolActivitySummary,
  45. } from '../../../core/message-segments';
  46. import { Message } from '../../../core/api/models';
  47. import { sessionPresence } from '../../../core/agent-liveness';
  48. import { TaskPulseService } from '../../../core/task-pulse.service';
  49. import { BackButtonService } from '../../../core/back-button.service';
  50. import { fileIdentity } from '../../../core/s3-link';
  51. import { mergeConsecutiveBodies } from '../../../core/message-merge';
  52. import {
  53. AssistantTurn,
  54. isTurnStalled,
  55. isTurnTimedOut,
  56. STALL_MS,
  57. TURN_TIMEOUT_MS,
  58. turnsFromDm,
  59. } from '../../../core/assistant-turn';
  60. import { AlertService } from '../../../core/alert.service';
  61. import { AssistantTurnComponent } from '../../../components/domain/assistant-turn/assistant-turn';
  62. import { UiMPullRefresh } from '../../../ui/mobile/components/pull-refresh/pull-refresh';
  63. /**
  64. * 会话消息行:普通消息 or 已合并的终端活动组。
  65. * 与桌面端 `desktop/pages/chat/chat.ts` 的 `MessageRow` 同构。
  66. */
  67. /** 触顶阈值:滚动到距顶部 80px 内即自动加载更早消息(与 PC 一致) */
  68. const TOP_LOAD_PX = 80;
  69. type MessageRow =
  70. | { kind: 'msg'; key: string; message: Message }
  71. | { kind: 'tool'; key: string; block: Extract<Block, { kind: 'process' }> }
  72. /** 回合:一次提问的全部 agent 输出合成一条气泡(2026-11-05) */
  73. | {
  74. kind: 'turn';
  75. key: string;
  76. blocks: TurnBlock[];
  77. open: boolean;
  78. collapsed: boolean;
  79. seconds: number;
  80. };
  81. /** 卡片渲染行(2026-11-07):用户消息一行,AI 一整轮一张卡 */
  82. type AiRow =
  83. | { kind: 'msg'; key: string; message: Message }
  84. | { kind: 'turn'; key: string; turn: AssistantTurn };
  85. /** 回合内部的一块:正文一条,或一组工具执行过程 */
  86. type TurnBlock =
  87. | { kind: 'msg'; key: string; message: Message }
  88. | { kind: 'tool'; key: string; block: Extract<Block, { kind: 'process' }> };
  89. type SheetTab = 'task' | 'file' | 'deliver' | 'state';
  90. /**
  91. * 会话详情(Demo 06 + 07 成果抽屉)
  92. *
  93. * 全屏路由(无 TabBar):顶栏固定 + 消息区独立滚动 + 底部输入坞固定。
  94. * 所有收发状态来自 `ChatService`(与桌面同一状态机),本页只做编排:
  95. * · `:id` = agentId;`:sessionId` 缺省 = 打开该容器最近一条会话
  96. * · 无 sessionId 且容器下没有会话 → `startBlank()` 建一条「新建对话」
  97. */
  98. @Component({
  99. selector: 'app-mb-chat-page',
  100. changeDetection: ChangeDetectionStrategy.OnPush,
  101. imports: [UserNoticePipe,
  102. MAppBarComponent,
  103. MDockComponent,
  104. MDrawerComponent,
  105. MNewChatSheetComponent,
  106. MProjectSwitcherComponent,
  107. TitleEditorComponent,
  108. MEmptyComponent,
  109. MMsgComponent,
  110. MBadgeComponent,
  111. FilePreviewComponent,
  112. ImageLightboxComponent,
  113. LockScrollDirective,
  114. AssistantTurnComponent,
  115. UiMPullRefresh,
  116. ],
  117. template: `
  118. <div class="m-page m-page--fixed">
  119. <app-m-app-bar
  120. [title]="title()"
  121. [subtitle]="subtitle()"
  122. [back]="true"
  123. [rightCount]="2"
  124. [titleEditable]="true"
  125. (backTap)="back()"
  126. (titleTap)="openTitleEditor()"
  127. >
  128. <!--
  129. 会话切换(2026-11-09):抽屉组件早就引入了却没用,导致移动端进了
  130. 一条会话就出不去 —— 只能退回消息列表再进,等于不能切会话。
  131. -->
  132. <button barRight type="button" class="m-fab" aria-label="切换会话" (click)="drawerOpen.set(true)">
  133. <i class="fa-solid fa-bars-staggered" aria-hidden="true"></i>
  134. </button>
  135. <button barRight type="button" class="m-fab" aria-label="查看成果与状态" (click)="sheetOpen.set(true)">
  136. <i class="fa-solid fa-folder-open" aria-hidden="true"></i>
  137. </button>
  138. </app-m-app-bar>
  139. <app-m-drawer
  140. [open]="drawerOpen()"
  141. [activeSessionId]="chat.sessionId()"
  142. [quickNewAgentId]="chat.agent()?.id ?? null"
  143. (close)="drawerOpen.set(false)"
  144. (newChat)="startNewChatInProject(chat.currentSession()?.workspaceId ?? null)"
  145. (newChatWithWs)="startNewChatInProject($event)"
  146. (quickNew)="newChatInCurrent($event)"
  147. />
  148. <!-- 试用到期(2026-12-03):门禁已拦,深链直达时也给明确原因 -->
  149. @if (chat.agent()?.trialExpired) {
  150. <div class="trial-expired-bar" role="alert">
  151. <i class="fa-solid fa-hourglass-end" aria-hidden="true"></i>
  152. <span>两天试用已到期,开通套餐后继续使用</span>
  153. <button type="button" class="trial-expired-btn" (click)="goPlan()">去开通</button>
  154. </div>
  155. }
  156. @if (chat.connection() === 'disconnected' && chat.state() !== 'loading') {
  157. <button type="button" class="m-conn-bar" (click)="reconnect()">
  158. <i class="fa-solid fa-plug-circle-exclamation" aria-hidden="true"></i>
  159. 连接已断开,点击重连
  160. </button>
  161. }
  162. <!--
  163. 回环提示(2026-11-09):桌面早就有,移动端一直没有 ——
  164. 手机上看不到「为什么没回复」,只会一脸茫然。
  165. -->
  166. @if (loop.paused()) {
  167. <div class="m-loop-bar" role="status">
  168. <div class="m-loop-text">
  169. <i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i>
  170. <span>检测到自动对话循环,已暂停:{{ loop.pauseDetail() }}</span>
  171. </div>
  172. <button type="button" class="m-loop-act" (click)="loop.resume()">继续协作</button>
  173. </div>
  174. }
  175. <div class="m-chat-body" #scroller (scroll)="onScroll($event)">
  176. <!-- 下拉刷新(2026-12-02 用户裁决:主要页面都要):强制重开当前会话 -->
  177. <ui-m-pull-refresh [onRefresh]="onPullRefresh">
  178. @switch (chat.state()) {
  179. @case ('loading') {
  180. <div class="m-loading" aria-busy="true" aria-label="正在加载消息">
  181. <span class="m-typing"><i></i><i></i><i></i></span>
  182. </div>
  183. }
  184. @case ('error') {
  185. <app-m-empty
  186. icon="fa-solid fa-triangle-exclamation"
  187. title="消息加载失败"
  188. [description]="(chat.error() ?? '') | userNotice"
  189. [retryable]="true"
  190. (retry)="reconnect()"
  191. />
  192. }
  193. @case ('empty') {
  194. @if (preparingRoom()) {
  195. <!-- 新建会话建房间中(2026-11-13):给出明确反馈,避免「点了没反应」 -->
  196. <div class="m-loading" role="status" aria-live="polite" aria-label="正在准备会话">
  197. <span class="m-typing"><i></i><i></i><i></i></span>
  198. <p class="m-loading-text">正在准备会话…</p>
  199. </div>
  200. } @else if (chat.emptyReason() === 'removed') {
  201. <!-- 已软删会话(2026-11-09 用户裁决):URL 直达也不认领 -->
  202. <app-m-empty
  203. icon="fa-solid fa-trash-can"
  204. title="该会话已删除"
  205. description="这条对话已经被删除,无法再查看或继续发送消息。"
  206. />
  207. } @else if (chat.emptyReason() === 'blank') {
  208. <!--
  209. 空壳会话(2026-11-12):已翻到房间最早、目录里有这条、但一条消息都没有。
  210. 必须与「暂时取不到」分开说,否则用户会一直等、以为数据丢了。
  211. -->
  212. <app-m-empty
  213. icon="fa-solid fa-inbox"
  214. title="这条对话没有保存任何消息"
  215. description="会话记录还在,但服务器上找不到它的任何消息内容。"
  216. />
  217. } @else if (chat.emptyReason() === 'unloaded') {
  218. <!--
  219. 有会话但历史取不到(2026-11-09):不能伪装成「开始新的对话」。
  220. 🔴 2026-11-13 补「重试」(真机实测):移动网络下回溯请求可能失败,
  221. 原先没有重试入口,用户只能一直看着这句话。
  222. -->
  223. <app-m-empty
  224. icon="fa-solid fa-inbox"
  225. title="这个会话的消息暂时没加载出来"
  226. description="可能是网络波动导致历史读取失败。点下面重试,或直接发消息继续对话。"
  227. [retryable]="true"
  228. (retry)="retry()"
  229. />
  230. } @else {
  231. <app-m-empty
  232. icon="fa-solid fa-comments"
  233. title="开始新的对话"
  234. description="发一条消息,数字生命就会开始工作"
  235. />
  236. }
  237. }
  238. @default {
  239. <!-- 触顶自动加载(不再需要按钮);这里只显示加载指示 -->
  240. @if (chat.paginating()) {
  241. <p class="m-load-more" aria-live="polite">
  242. <i class="fa-solid fa-circle-notch fa-spin" aria-hidden="true"></i>
  243. 正在加载更早的消息…
  244. </p>
  245. }
  246. <!--
  247. 回合聚合(2026-11-05):一次提问产生的多条 agent 消息合成**一条气泡**,
  248. 后到内容往里追加。过程行折叠在气泡顶部,执行中自动展开、完成后收起。
  249. -->
  250. <!--
  251. 卡片渲染(2026-11-07 用户需求):一轮 = 一张卡,
  252. 与桌面端共用 app-assistant-turn。用户消息仍走 app-m-msg,保持移动观感。
  253. -->
  254. @for (row of aiRows(); track row.key) {
  255. @if (row.kind === 'turn') {
  256. <!--
  257. 2026-12-02 用户裁决:恢复桌面同款等待反馈(删掉 hideRunningHint)。
  258. 此前(674428a)隐藏了「已处理 Ns · 继续处理任务过程」,声称由
  259. 「顶栏紫色进度条」替代 —— 但那个进度条从未实现,移动端等待期
  260. 变成零反馈(用户实测:回复动画全没了)。
  261. -->
  262. <app-assistant-turn
  263. [turn]="row.turn"
  264. [grouped]="false"
  265. (preview)="openFile($event)"
  266. (openTask)="goTask($event)"
  267. />
  268. } @else {
  269. <app-m-msg
  270. [message]="row.message"
  271. (retry)="retryMessage($event)"
  272. (openTask)="goTask($event)"
  273. />
  274. }
  275. }
  276. }
  277. }
  278. <!-- 与桌面同口径:回合卡已经在显示等待文案时,这里不再重复一条(2026-11-09) -->
  279. <!-- 2026-12-02 用户裁决:不展示容器命名(slug 感太重),固定文案「对方」 -->
  280. @if (chat.peerTyping() && aiRows().length === 0) {
  281. <p class="m-typing-line">对方正在输入…</p>
  282. }
  283. </ui-m-pull-refresh>
  284. </div>
  285. <div class="m-composer-area">
  286. <!--
  287. 容器连接中断提示(2026-12-03,用户实测:网关重启/崩溃时「输出中」无限转圈)。
  288. 信号 = Matrix presence(网关死 → /sync 断 → offline,秒~分钟级),
  289. 不用容器心跳(1 小时周期且网关崩了照发,判不出来)。
  290. 恢复在线后此条自动消失;Hermes 会从 sync 断点补收消息,通常无需重发。
  291. -->
  292. @if (connectionInterrupted()) {
  293. <div class="conn-interrupt" role="alert">
  294. <i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i>
  295. <span>容器连接中断,回复可能延迟或未送达</span>
  296. <button type="button" class="conn-interrupt-btn" (click)="resendPendingTurn()">重新发送</button>
  297. </div>
  298. }
  299. <!-- 待发消息持有条已移除(2026-11-14 用户裁决「永远不拦,直接发」) -->
  300. <!-- 待发附件:图片出缩略图(与 PC 端同构),其余出文件名 chip -->
  301. @if (chat.pendingFiles().length > 0) {
  302. <div class="m-pending" role="list" aria-label="待发送附件">
  303. @for (f of chat.pendingFiles(); track f.id) {
  304. @if (f.previewUrl) {
  305. <div class="m-pending-card" role="listitem">
  306. <img [src]="f.previewUrl" [alt]="f.file.name" class="m-pending-img" />
  307. <button
  308. type="button"
  309. class="m-pending-x"
  310. [attr.aria-label]="'移除 ' + f.file.name"
  311. (click)="chat.unstageFile(f.id)"
  312. >
  313. <i class="fa-solid fa-xmark" aria-hidden="true"></i>
  314. </button>
  315. </div>
  316. } @else {
  317. <span class="m-pending-item" role="listitem">
  318. <i class="fa-solid fa-paperclip" aria-hidden="true"></i>
  319. <span class="m-pending-name">{{ f.file.name }}</span>
  320. <button
  321. type="button"
  322. [attr.aria-label]="'移除 ' + f.file.name"
  323. (click)="chat.unstageFile(f.id)"
  324. >
  325. <i class="fa-solid fa-xmark" aria-hidden="true"></i>
  326. </button>
  327. </span>
  328. }
  329. }
  330. </div>
  331. }
  332. <!--
  333. 2026-12-02 用户裁决:输入区不展示容器命名 ——
  334. 删掉 [target](m-dock 的命名胶囊自动隐藏),placeholder 回到默认「发消息…」。
  335. -->
  336. <app-m-dock
  337. [draft]="chat.draft()"
  338. [disabled]="preparingRoom() || chat.state() === 'loading' || !!chat.agent()?.trialExpired"
  339. [hint]="sendHint()"
  340. [sending]="chat.sending()"
  341. [uploading]="chat.uploading()"
  342. [pct]="chat.uploadPct()"
  343. [stage]="chat.uploadPhase()"
  344. [hasAttachments]="chat.pendingFiles().length > 0"
  345. (draftChange)="chat.setDraft($event)"
  346. (send)="send($event)"
  347. (attach)="chat.stageFiles($event)"
  348. >
  349. <!--
  350. 项目切换器放进工具行(2026-11-23 用户要求):
  351. 原来是输入框上方独占一整行,纯占高度。现在收到附件按钮右侧同一行。
  352. dockTools 属性是 m-dock 里 ng-content select 的投影锚点。
  353. -->
  354. <ng-container ngProjectAs="[dockTools]">
  355. <app-m-project-switcher
  356. [(open)]="projectPickerOpen"
  357. [currentWorkspaceId]="chat.currentSession()?.workspaceId ?? null"
  358. [currentSessionId]="chat.currentSession()?.id ?? null"
  359. (openSession)="openProjectSession($event)"
  360. (newConversation)="startNewChatInProject($event)"
  361. />
  362. </ng-container>
  363. </app-m-dock>
  364. </div>
  365. </div>
  366. <!-- 全屏预览层(2026-11-03):点会话内文件/成果都走这里,不再新开标签页 -->
  367. <app-image-lightbox
  368. [open]="!!lightbox()"
  369. [url]="lightbox()?.url ?? ''"
  370. [name]="lightbox()?.name ?? ''"
  371. [size]="lightbox()?.size ?? 0"
  372. (closed)="lightbox.set(null)"
  373. />
  374. <app-file-preview
  375. [open]="!!preview()"
  376. [url]="preview()?.url ?? ''"
  377. [name]="preview()?.name ?? ''"
  378. [mimeType]="preview()?.mimeType ?? ''"
  379. mode="modal"
  380. (closed)="preview.set(null)"
  381. />
  382. <app-m-new-chat
  383. [open]="projectChatOpen()"
  384. (openChange)="onProjectChatOpenChange($event)"
  385. [(workspaceId)]="pendingProjectId"
  386. (created)="createProjectChat($event)"
  387. />
  388. <!--
  389. 会话标题编辑(2026-11-23 用户要求)
  390. 标题点击进来改显示名,只改房间名,不动消息内容。
  391. -->
  392. <app-m-title-editor
  393. [open]="titleEditorOpen()"
  394. [initial]="title()"
  395. (save)="onTitleSave($event)"
  396. (cancel)="titleEditorOpen.set(false)"
  397. />
  398. <!-- 成果抽屉(Demo 07:任务 / 文件 / 成果 / 状态) -->
  399. @if (sheetOpen()) {
  400. <div class="m-sheet-root" role="dialog" aria-modal="true" aria-label="会话面板" [appLockScroll]="true">
  401. <div class="m-sheet-mask" (click)="sheetOpen.set(false)"></div>
  402. <section class="m-sheet">
  403. <div class="m-grabber" aria-hidden="true"></div>
  404. <header class="m-sheet-head">
  405. <h2>{{ title() }}</h2>
  406. <button type="button" class="m-sheet-x" aria-label="关闭" (click)="sheetOpen.set(false)">
  407. <i class="fa-solid fa-xmark" aria-hidden="true"></i>
  408. </button>
  409. </header>
  410. <div class="m-sheet-tabs" role="tablist">
  411. @for (t of sheetTabs; track t.value) {
  412. <button
  413. type="button"
  414. role="tab"
  415. class="m-chip"
  416. [class.on]="sheetTab() === t.value"
  417. [attr.aria-selected]="sheetTab() === t.value"
  418. (click)="sheetTab.set(t.value)"
  419. >
  420. {{ t.label }}
  421. </button>
  422. }
  423. </div>
  424. <div class="m-sheet-body">
  425. @switch (sheetTab()) {
  426. @case ('task') {
  427. @if (relatedTasks().length > 0) {
  428. <ul class="m-list">
  429. @for (t of relatedTasks(); track t.id) {
  430. <li>
  431. <button
  432. type="button"
  433. class="m-row"
  434. [class.hl]="railHighlight() === t.id"
  435. (click)="goTask(t.id)"
  436. >
  437. <span class="m-row-body">
  438. <span class="m-row-t1">{{ t.title }}</span>
  439. <span class="m-row-t2">{{ t.updatedAt || '—' }}</span>
  440. </span>
  441. <app-m-badge [tone]="taskTone(t)">{{ taskText(t) }}</app-m-badge>
  442. </button>
  443. </li>
  444. }
  445. </ul>
  446. } @else {
  447. <app-m-empty title="暂无任务" [compact]="true" />
  448. }
  449. }
  450. @case ('file') {
  451. @if (files().length > 0) {
  452. <ul class="m-list">
  453. @for (f of files(); track f.url + f.name) {
  454. <li>
  455. <!-- 点开走全屏预览(2026-11-03),不再新开标签页 -->
  456. <button type="button" class="m-row" (click)="openFile(f)">
  457. <i class="fa-solid fa-file" aria-hidden="true"></i>
  458. <span class="m-row-body">
  459. <span class="m-row-t1">{{ f.name }}</span>
  460. <span class="m-row-t2">{{ fmtSize(f.size) }}</span>
  461. </span>
  462. <i class="fa-solid fa-chevron-right m-chev" aria-hidden="true"></i>
  463. </button>
  464. </li>
  465. }
  466. </ul>
  467. } @else {
  468. <app-m-empty title="暂无文件" [compact]="true" />
  469. }
  470. }
  471. @case ('deliver') {
  472. <!--
  473. 未上云提示(2026-11-09),与桌面 session-rail 同口径。
  474. 附件没有 url 时原来静默不显示,用户以为文件丢了。
  475. -->
  476. @if (notOnCloudCount() > 0) {
  477. <p class="m-rail-warn" role="status">
  478. <i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i>
  479. 有 {{ notOnCloudCount() }} 个成果文件未上传云盘,暂时无法查看
  480. </p>
  481. }
  482. @if (deliverables().length > 0) {
  483. @for (d of deliverables(); track d.id) {
  484. <div class="m-deliver">
  485. <div class="m-deliver-head">
  486. <span class="m-row-t1">{{ d.title }}</span>
  487. <span class="m-row-t2">{{ d.version || '' }} · {{ d.deliveredAt }}</span>
  488. </div>
  489. @if (d.artifacts.length > 0) {
  490. <ul class="m-list">
  491. <!-- 遍历全部产物(原实现只取 artifacts[0],其余看不到) -->
  492. @for (a of d.artifacts; track a.url || a.name) {
  493. <li>
  494. <button type="button" class="m-row" (click)="openFile(a)">
  495. <i class="fa-solid fa-paperclip" aria-hidden="true"></i>
  496. <span class="m-row-body">
  497. <span class="m-row-t1">{{ a.name }}</span>
  498. <span class="m-row-t2">{{ a.type || '' }}</span>
  499. </span>
  500. <i class="fa-solid fa-chevron-right m-chev" aria-hidden="true"></i>
  501. </button>
  502. </li>
  503. }
  504. </ul>
  505. } @else {
  506. <p class="m-deliver-empty">暂无可用产物</p>
  507. }
  508. </div>
  509. }
  510. } @else {
  511. <app-m-empty title="暂无成果" [compact]="true" />
  512. }
  513. }
  514. @default {
  515. <dl class="m-kv">
  516. <dt>状态</dt>
  517. <!-- 统一口径(2026-11-08):原先直接渲染 statusText ?? status,英文 id 会露出 -->
  518. <dd>{{ agentState()?.text ?? '—' }}</dd>
  519. <dt>当前任务</dt>
  520. <dd>{{ agent()?.currentTask || '—' }}</dd>
  521. <dt>最近在线</dt>
  522. <dd>{{ heartbeatText() }}</dd>
  523. <dt>连接</dt>
  524. <dd>{{ chat.connection() === 'connected' ? '已连接' : '未连接' }}</dd>
  525. <dt>会话</dt>
  526. <dd>{{ title() }}</dd>
  527. </dl>
  528. }
  529. }
  530. </div>
  531. </section>
  532. </div>
  533. }
  534. `,
  535. styles: [
  536. `
  537. :host {
  538. display: block;
  539. }
  540. .m-page {
  541. display: flex;
  542. flex-direction: column;
  543. height: 100dvh;
  544. background: var(--surface);
  545. }
  546. .m-fab {
  547. display: grid;
  548. place-items: center;
  549. width: var(--touch-min);
  550. height: var(--touch-min);
  551. border: 0;
  552. border-radius: var(--r-tag);
  553. background: transparent;
  554. box-shadow: none;
  555. color: var(--ink);
  556. font-size: var(--fs-icon);
  557. cursor: pointer;
  558. }
  559. /* 试用到期提示条(2026-12-03):与连接中断条同风格,左侧文案 + 右侧去开通 */
  560. .trial-expired-bar {
  561. display: flex;
  562. align-items: center;
  563. gap: var(--sp-2);
  564. width: calc(100% - var(--mob-gutter) * 2);
  565. margin: var(--sp-2) var(--mob-gutter) 0;
  566. padding: var(--sp-2) var(--sp-3);
  567. border: 1px solid var(--warning);
  568. border-radius: var(--r-md);
  569. background: var(--warning-subtle);
  570. color: var(--warning);
  571. font-size: var(--fs-12);
  572. line-height: 1.4;
  573. }
  574. .trial-expired-bar > span {
  575. flex: 1;
  576. min-width: 0;
  577. }
  578. .trial-expired-btn {
  579. flex: none;
  580. min-height: 32px;
  581. padding: 0 var(--sp-3);
  582. border: 1px solid var(--warning);
  583. border-radius: 8px;
  584. background: transparent;
  585. color: var(--warning);
  586. font-size: var(--fs-12);
  587. cursor: pointer;
  588. }
  589. .m-conn-bar {
  590. display: flex;
  591. align-items: center;
  592. justify-content: center;
  593. gap: var(--sp-2);
  594. width: calc(100% - var(--mob-gutter) * 2);
  595. margin: 0 var(--mob-gutter);
  596. padding: var(--sp-2) var(--sp-3);
  597. border: 1px solid var(--warning);
  598. border-radius: var(--r-md);
  599. background: var(--warning-subtle);
  600. color: var(--warning);
  601. font: inherit;
  602. font-size: var(--fs-12);
  603. cursor: pointer;
  604. }
  605. /* 回环提示条(与 m-conn-bar 同一套 warning 令牌,但主体是说明 + 独立动作按钮) */
  606. .m-loop-bar {
  607. display: flex;
  608. align-items: center;
  609. gap: var(--sp-2);
  610. width: calc(100% - var(--mob-gutter) * 2);
  611. margin: 0 var(--mob-gutter) var(--sp-2);
  612. padding: var(--sp-2) var(--sp-3);
  613. border: 1px solid var(--warning);
  614. border-radius: var(--r-md);
  615. background: var(--warning-subtle);
  616. color: var(--warning); font-size: var(--fs-12);
  617. }
  618. .m-loop-text {
  619. display: flex;
  620. align-items: center;
  621. gap: var(--sp-2);
  622. flex: 1;
  623. min-width: 0;
  624. } .m-loop-text span {
  625. /* 提示较长,允许换行但不挤掉按钮 */
  626. overflow-wrap: anywhere;
  627. }
  628. /* 未上云的成果提示(2026-11-09),与桌面 rail-warn 同口径 */
  629. .m-rail-warn {
  630. display: flex;
  631. align-items: flex-start;
  632. gap: var(--sp-1);
  633. margin: var(--sp-2) var(--mob-gutter) 0;
  634. padding: var(--sp-2) var(--sp-3);
  635. border-radius: var(--r-tag);
  636. background: var(--warning-subtle);
  637. color: var(--warning);
  638. font-size: var(--fs-13);
  639. line-height: 1.5;
  640. }
  641. .m-loop-act {
  642. flex: none;
  643. /* 触达区 ≥44px(WCAG 2.2 AA) */
  644. min-height: 44px;
  645. padding: 0 var(--sp-3);
  646. border: 1px solid var(--warning);
  647. border-radius: var(--r-sm);
  648. background: transparent;
  649. color: var(--warning);
  650. font: inherit;
  651. font-size: var(--fs-13);
  652. cursor: pointer;
  653. }
  654. .m-turn {
  655. display: flex;
  656. flex-direction: column;
  657. gap: var(--sp-3);
  658. }
  659. .m-turn-head {
  660. display: inline-flex;
  661. align-items: center;
  662. gap: var(--sp-2);
  663. align-self: flex-start;
  664. min-height: 28px;
  665. padding: 0 var(--sp-3);
  666. border: 1px solid var(--edge);
  667. border-radius: var(--r-tag);
  668. background: var(--surface-2);
  669. color: var(--muted);
  670. font: inherit;
  671. font-size: var(--fs-12);
  672. cursor: pointer;
  673. }
  674. .m-exec {
  675. color: var(--info);
  676. }
  677. .m-chat-body {
  678. flex: 1;
  679. min-height: 0;
  680. overflow-y: auto;
  681. -webkit-overflow-scrolling: touch;
  682. display: flex;
  683. flex-direction: column;
  684. gap: var(--sp-4);
  685. padding: var(--sp-3) var(--mob-gutter) var(--sp-6);
  686. }
  687. .m-load-more {
  688. display: flex;
  689. align-items: center;
  690. justify-content: center;
  691. gap: var(--sp-2);
  692. margin: 0;
  693. padding: var(--sp-2);
  694. color: var(--muted);
  695. font-size: var(--fs-12);
  696. }
  697. .m-typing-line {
  698. margin: 0;
  699. color: var(--muted);
  700. font-size: var(--fs-12);
  701. }
  702. .m-loading {
  703. display: grid;
  704. place-items: center;
  705. gap: var(--sp-3);
  706. padding: var(--sp-8);
  707. }
  708. /* 建会话/加载中的说明文字(2026-11-13) */
  709. .m-loading-text {
  710. margin: 0;
  711. font-size: var(--fs-13);
  712. color: var(--muted);
  713. }
  714. .m-typing {
  715. display: inline-flex;
  716. gap: 4px;
  717. }
  718. .m-typing i {
  719. width: 6px;
  720. height: 6px;
  721. border-radius: var(--r-tag);
  722. background: var(--edge-strong);
  723. animation: m-bounce 1s infinite ease-in-out;
  724. }
  725. .m-typing i:nth-child(2) {
  726. animation-delay: 0.15s;
  727. }
  728. .m-typing i:nth-child(3) {
  729. animation-delay: 0.3s;
  730. }
  731. @keyframes m-bounce {
  732. 0%,
  733. 80%,
  734. 100% {
  735. transform: translateY(0);
  736. opacity: 0.4;
  737. }
  738. 40% {
  739. transform: translateY(-4px);
  740. opacity: 1;
  741. }
  742. }
  743. .m-composer-area {
  744. /* 待发消息提示条样式已移除(2026-11-14 持有条机制下线) */
  745. flex: none;
  746. padding-bottom: calc(var(--mob-safe-bottom) + var(--sp-3));
  747. /*
  748. * 2026-12-02 用户裁决:
  749. * ① 删掉 background: var(--surface) —— 输入区背景透明融入消息流
  750. * (桌面端同区域就是透明的),坞体卡片自带 --surface-2 不变;
  751. * ② 删掉 padding-inline: var(--mob-gutter) —— m-dock 自身已有
  752. * margin-inline: var(--mob-gutter),两层叠加让输入框比消息流窄一截。
  753. */
  754. }
  755. /* 容器连接中断提示条(2026-12-03):与 m-dock 同宽(对齐 gutter) */
  756. .conn-interrupt {
  757. display: flex;
  758. align-items: center;
  759. gap: var(--sp-2);
  760. margin: 0 var(--mob-gutter) var(--sp-2);
  761. padding: var(--sp-2) var(--sp-3);
  762. border-radius: 10px;
  763. background: var(--warning-subtle);
  764. color: var(--warning);
  765. font-size: var(--fs-12);
  766. line-height: 1.4;
  767. }
  768. .conn-interrupt > span {
  769. flex: 1;
  770. min-width: 0;
  771. }
  772. .conn-interrupt-btn {
  773. flex: none;
  774. min-height: 32px;
  775. padding: 0 var(--sp-3);
  776. border: 1px solid var(--warning);
  777. border-radius: 8px;
  778. background: transparent;
  779. color: var(--warning);
  780. font-size: var(--fs-12);
  781. cursor: pointer;
  782. }
  783. .m-pending {
  784. display: flex;
  785. gap: var(--sp-2);
  786. padding: 0 var(--mob-gutter) var(--sp-2);
  787. overflow-x: auto;
  788. scrollbar-width: none;
  789. }
  790. .m-pending::-webkit-scrollbar {
  791. display: none;
  792. }
  793. /* 图片待发卡:缩略图 + 右上角移除 */
  794. .m-pending-card {
  795. position: relative;
  796. flex: none;
  797. width: 72px;
  798. height: 72px;
  799. border-radius: var(--r-md);
  800. overflow: hidden;
  801. border: 1px solid var(--edge);
  802. background: var(--surface-2);
  803. }
  804. .m-pending-img {
  805. width: 100%;
  806. height: 100%;
  807. object-fit: cover;
  808. display: block;
  809. }
  810. .m-pending-x {
  811. position: absolute;
  812. top: 2px;
  813. right: 2px;
  814. display: grid;
  815. place-items: center;
  816. width: var(--touch-min);
  817. height: var(--touch-min);
  818. padding: 0;
  819. border: 0;
  820. border-radius: var(--r-tag);
  821. background: color-mix(in srgb, var(--ink) 70%, transparent);
  822. color: var(--surface);
  823. font-size: var(--fs-10);
  824. cursor: pointer;
  825. }
  826. .m-pending-item {
  827. display: inline-flex;
  828. align-items: center;
  829. gap: var(--sp-2);
  830. max-width: 100%;
  831. padding: var(--sp-1) var(--sp-2);
  832. border: 1px solid var(--edge);
  833. border-radius: var(--r-sm);
  834. background: var(--surface);
  835. color: var(--ink-2);
  836. font-size: var(--fs-12);
  837. }
  838. .m-pending-name {
  839. max-width: 160px;
  840. overflow: hidden;
  841. text-overflow: ellipsis;
  842. white-space: nowrap;
  843. }
  844. .m-pending-item button {
  845. min-width: var(--touch-min);
  846. min-height: var(--touch-min);
  847. border: 0;
  848. background: none;
  849. color: var(--muted);
  850. cursor: pointer;
  851. padding: 0;
  852. }
  853. .m-sheet-root {
  854. position: fixed;
  855. inset: 0;
  856. z-index: var(--z-modal);
  857. }
  858. .m-sheet-mask {
  859. position: absolute;
  860. inset: 0;
  861. background: var(--overlay);
  862. }
  863. .m-sheet {
  864. position: absolute;
  865. left: 0;
  866. right: 0;
  867. bottom: 0;
  868. display: flex;
  869. flex-direction: column;
  870. /* 默认全屏(2026-11-03 用户要求):原来是 max-height:82%,内容矮时只占一小块 */
  871. height: 100dvh;
  872. max-height: 100dvh;
  873. padding-top: var(--mob-safe-top);
  874. padding-bottom: var(--mob-safe-bottom);
  875. border-radius: var(--r-sheet) var(--r-sheet) 0 0;
  876. box-sizing: border-box;
  877. background: var(--surface);
  878. box-shadow: var(--shadow-overlay);
  879. animation: m-sheet-in var(--motion-panel) var(--ease-standard);
  880. }
  881. .m-grabber {
  882. width: 36px;
  883. height: 4px;
  884. margin: var(--sp-2) auto;
  885. border-radius: var(--r-tag);
  886. background: var(--edge-strong);
  887. }
  888. .m-sheet-head {
  889. display: flex;
  890. align-items: center;
  891. gap: var(--sp-3);
  892. padding: var(--sp-2) var(--mob-gutter) var(--sp-3);
  893. }
  894. .m-sheet-head h2 {
  895. flex: 1;
  896. margin: 0;
  897. overflow: hidden;
  898. text-overflow: ellipsis;
  899. white-space: nowrap;
  900. color: var(--ink);
  901. font-size: var(--fs-17);
  902. }
  903. .m-sheet-x {
  904. display: grid;
  905. place-items: center;
  906. width: var(--touch-min);
  907. height: var(--touch-min);
  908. border: 0;
  909. border-radius: var(--r-tag);
  910. background: none;
  911. color: var(--muted);
  912. font-size: var(--fs-icon);
  913. cursor: pointer;
  914. }
  915. .m-sheet-tabs {
  916. display: flex;
  917. gap: var(--sp-2);
  918. padding: 0 var(--mob-gutter) var(--sp-3);
  919. overflow-x: auto;
  920. }
  921. .m-chip {
  922. flex: none;
  923. height: 34px;
  924. padding: 0 var(--sp-3);
  925. border: 1px solid var(--edge);
  926. border-radius: var(--r-tag);
  927. background: var(--surface);
  928. color: var(--ink-2);
  929. font: inherit;
  930. font-size: var(--fs-13);
  931. cursor: pointer;
  932. }
  933. .m-chip.on {
  934. border-color: var(--primary);
  935. background: var(--primary);
  936. color: var(--primary-content);
  937. font-weight: 600;
  938. }
  939. .m-sheet-body {
  940. overflow-y: auto;
  941. padding: 0 var(--mob-gutter) var(--sp-6);
  942. }
  943. .m-list {
  944. margin: 0;
  945. padding: 0;
  946. list-style: none;
  947. border: 1px solid var(--edge);
  948. border-radius: var(--r-lg);
  949. overflow: hidden;
  950. }
  951. .m-list > li + li {
  952. border-top: 1px solid var(--edge);
  953. }
  954. .m-row {
  955. display: flex;
  956. align-items: center;
  957. gap: var(--sp-3);
  958. width: 100%;
  959. min-height: 56px;
  960. padding: var(--sp-3) var(--sp-4);
  961. box-sizing: border-box;
  962. border: 0;
  963. background: var(--surface);
  964. color: var(--ink);
  965. font: inherit;
  966. text-align: left;
  967. text-decoration: none;
  968. cursor: pointer;
  969. }
  970. /* 深链定位高亮(2026-11-11):任务引用点进来时短暂标出是哪条 */
  971. .m-row.hl {
  972. background: var(--surface-hover);
  973. box-shadow: inset 3px 0 0 var(--primary);
  974. }
  975. .m-row-body {
  976. flex: 1;
  977. min-width: 0;
  978. }
  979. .m-row-t1,
  980. .m-row-t2 {
  981. display: block;
  982. overflow: hidden;
  983. text-overflow: ellipsis;
  984. white-space: nowrap;
  985. }
  986. .m-row-t1 {
  987. font-size: var(--fs-15);
  988. }
  989. .m-row-t2 {
  990. color: var(--muted);
  991. font-size: var(--fs-13);
  992. }
  993. .m-kv {
  994. display: grid;
  995. grid-template-columns: 96px 1fr;
  996. gap: var(--sp-2) var(--sp-3);
  997. margin: 0;
  998. padding: var(--sp-4);
  999. border: 1px solid var(--edge);
  1000. border-radius: var(--r-lg);
  1001. font-size: var(--fs-13);
  1002. }
  1003. .m-kv dt {
  1004. color: var(--muted);
  1005. }
  1006. .m-kv dd {
  1007. margin: 0;
  1008. color: var(--ink);
  1009. word-break: break-all;
  1010. }
  1011. /*
  1012. * 统一的弹层进场(2026-11-23):从底部上浮 40px + 淡入,240ms 标准缓动。
  1013. * 原来这里是「从屏幕外整个滑入 translateY(100%)」,与选择项目浮卡的
  1014. * 「浮起 24px」不一致 —— 同样是从底部出来,一个扫过整屏、一个只轻抬一下。
  1015. * 现在全端统一为「轻抬」:有方向感,又不制造长距离运动。
  1016. */
  1017. @keyframes m-sheet-in {
  1018. from {
  1019. transform: translateY(40px);
  1020. opacity: 0;
  1021. }
  1022. to {
  1023. transform: translateY(0);
  1024. opacity: 1;
  1025. }
  1026. }
  1027. @media (prefers-reduced-motion: reduce) {
  1028. .m-sheet,
  1029. .m-typing i {
  1030. animation: none;
  1031. }
  1032. }
  1033. `,
  1034. ],
  1035. })
  1036. export class MbChatPage implements OnDestroy {
  1037. private readonly route = inject(ActivatedRoute);
  1038. private readonly router = inject(Router);
  1039. private readonly tasksSvc = inject(TasksService);
  1040. private readonly sessionsSvc = inject(ChatSessionService);
  1041. private readonly view = inject(MobileChatViewService);
  1042. /** 成果列表构造(从 agent 消息附件生成) */
  1043. private readonly deliverablesSvc = inject(DeliverablesService);
  1044. /** 容器成果 → 会话台账的绑定兜底(2026-11-13) */
  1045. protected readonly fileBinding = inject(AgentFileBindingService);
  1046. protected readonly chat = inject(ChatService);
  1047. private readonly incomingShares = inject(ShareReceiveService);
  1048. protected readonly loop = inject(LoopGuardService);
  1049. /**
  1050. * 任务脉冲(2026-11-14 接入)。
  1051. *
  1052. * 桌面端聊天顶栏早就用 `pulse.describe()` 显示「正在处理…」,
  1053. * 手机端却只有「在线 / 正在回复」——用户在手机上根本看不出容器到底在不在干活。
  1054. * 这里补齐,与桌面端同一判据、同一文案来源。
  1055. */
  1056. protected readonly pulse = inject(TaskPulseService);
  1057. protected readonly sheetOpen = signal(false);
  1058. protected readonly projectPickerOpen = signal(false);
  1059. protected readonly projectChatOpen = signal(false);
  1060. protected readonly pendingProjectId = signal<string | null>(null);
  1061. /** 图片走灯箱 */
  1062. protected readonly lightbox = signal<{ url: string; name: string; size: number } | null>(null);
  1063. /**
  1064. * 正在为新建会话开独立房间(2026-11-13)。
  1065. *
  1066. * 🔴 桌面端在「新建对话」弹窗里显示「正在准备会话…」,移动端没有对应位置 ——
  1067. * 点选容器后面板立刻关闭,要等 0.6~0.7 秒建房完成才跳转,
  1068. * 这段时间屏幕上什么都没发生,用户以为点了没反应(真机实测反馈)。
  1069. * 这里在会话页给出明确反馈。
  1070. */
  1071. protected readonly preparingRoom = signal(false);
  1072. /**
  1073. * 发送按钮的提示(2026-11-13)。
  1074. *
  1075. * 忙碌时明确告知「发送会打断当前任务」——实测确认的行为
  1076. * (容器 `busy_input_mode=interrupt`,0.7 秒内打断并响应)。
  1077. */
  1078. readonly sendHint = computed(() =>
  1079. this.chat.sessionBusy() ? '发送将打断当前任务' : '',
  1080. );
  1081. /** 其余文件走全屏预览 */
  1082. protected readonly preview = signal<{ url: string; name: string; mimeType: string } | null>(null);
  1083. protected readonly sheetTab = signal<SheetTab>('task');
  1084. /**
  1085. * 抽屉里需要高亮定位的任务 id(2026-11-11)。
  1086. *
  1087. * 「任务」页路由下线后,消息里的任务引用改为「打开抽屉 + 定位」,
  1088. * 与桌面 `openRailAt()` 同口径,2 秒后自动清空。
  1089. */
  1090. protected readonly railHighlight = signal<string | null>(null);
  1091. private railHighlightTimer: ReturnType<typeof setTimeout> | null = null;
  1092. /** 抽屉在本页不使用(返回即可),保留导入以便后续「会话切换」扩展 */
  1093. protected readonly drawerOpen = signal(false);
  1094. protected readonly sheetTabs: { value: SheetTab; label: string }[] = [
  1095. { value: 'task', label: '任务' },
  1096. { value: 'file', label: '文件' },
  1097. { value: 'deliver', label: '成果' },
  1098. { value: 'state', label: '状态' },
  1099. ];
  1100. protected readonly fmtSize = fmtSize;
  1101. protected readonly agent = computed(() => this.chat.agent());
  1102. /* agentName 已删除(2026-12-02 用户裁决:移动端会话页不展示容器命名) */
  1103. /**
  1104. * 容器离线 + 本端还有没等到回复的回合 → 显示「连接中断」提示条(2026-12-03)。
  1105. *
  1106. * 判定用 `chat.agentPresence()`(Matrix presence,秒~分钟级)而**不是**容器心跳
  1107. * (1 小时周期且与网关进程无关,网关崩了照发)。
  1108. * `'unknown'`(sync 未就绪)不告警,避免进页瞬间误报。
  1109. */
  1110. protected readonly connectionInterrupted = computed(() => {
  1111. if (this.chat.agentPresence() !== 'offline') return false;
  1112. return (
  1113. this.chat.awaitingReplySince() > 0 ||
  1114. this.aiRows().some((r) => r.kind === 'turn' && r.turn.live)
  1115. );
  1116. });
  1117. /**
  1118. * 「连接中断」提示条上的重新发送:取最后一个回合的用户原文重发(2026-12-03)。
  1119. *
  1120. * 注意:Hermes 恢复后会从 sync 断点补收消息,多数情况**不需要**重发;
  1121. * 这个按钮是「等了很久还没恢复」时的逃生口,代价是恢复后可能收到两条回复。
  1122. */
  1123. protected resendPendingTurn(): void {
  1124. const turns: AssistantTurn[] = [];
  1125. for (const r of this.aiRows()) if (r.kind === 'turn') turns.push(r.turn);
  1126. const text = [...turns].reverse().find((t) => t.userMessage?.text?.trim())?.userMessage?.text?.trim();
  1127. if (!text) return;
  1128. void this.chat.sendText(text);
  1129. }
  1130. /**
  1131. * 消息 → 渲染行:**连续的终端活动消息合并成一个折叠组**。
  1132. *
  1133. * 与桌面端同一套规则(`desktop/pages/chat/chat.ts` 的 `messageRows`):
  1134. * · 容器把 Hermes 每一步都作为独立消息发出(💻 terminal + 命令)
  1135. * · 相邻且都属于终端活动 → 合成一组;遇到正常对话立即断开
  1136. *
  1137. * 🔴 组 key 用**组内第一条消息的 id**,不能用下标:
  1138. * 流式追加时下标会变,导致同组被销毁重建(内容闪烁)。
  1139. */
  1140. /**
  1141. * 消息 → 渲染行(2026-11-05 改为**回合聚合**)。
  1142. *
  1143. * ## 变化
  1144. *
  1145. * 原来:每条 agent 消息一个气泡 → 一条回答被容器拆成 2~3 条,读起来断续。
  1146. * 现在:**一次提问的所有 agent 输出合成一个回合(一条气泡)**,内容往里追加。
  1147. *
  1148. * ## 边界
  1149. *
  1150. * `buildTurns` 负责切分(用户消息锚点 + typing 结束静默 3 秒),
  1151. * 本方法只负责把回合映射成渲染行 —— 逻辑分离,便于单测。
  1152. *
  1153. * ## 兼容
  1154. *
  1155. * 用户消息仍逐条渲染;回合内的过程行(💻 terminal 等)折叠到回合顶部。
  1156. */
  1157. /**
  1158. * 渲染行(2026-11-07 用户需求):AI 的一整轮合并成一张卡。
  1159. *
  1160. * 与桌面端共用 `app-assistant-turn` —— 用户裁决「复用同一个组件」,
  1161. * 移动端差异(触达区 44px、字号 ≥16px、段间距)由组件内的
  1162. * `bp.below-mobile` 分支处理,两处渲染逻辑保持单一来源。
  1163. */
  1164. protected readonly aiRows = computed<AiRow[]>(() => {
  1165. const out: AiRow[] = [];
  1166. /*
  1167. * 🔴 依赖 `clockTick` 而不是 `now`(2026-11-10,与桌面端同口径)。
  1168. *
  1169. * 原来这里读 `this.now()`,于是时钟每秒推进都会让**整页 aiRows 重算**,
  1170. * 每个 turn 对象都是新引用 → `app-assistant-turn` 的 input 变化 →
  1171. * 流式推进的 `shownMap` 可能被重置,正文从头重放。
  1172. * `clockTick` 是个计数器:每秒变一次,但只让**读它的地方**重算,
  1173. * 回合数据本身只在消息变化时重建。
  1174. */
  1175. this.clockTick();
  1176. const now = Date.now();
  1177. /*
  1178. * 🔴 跨回合全局文件去重(2026-11-18 用户裁决「全局去重」)。
  1179. *
  1180. * ## 现象
  1181. *
  1182. * 容器在第 1 回合发了 `table.html`,第 2 回合又发了一次(重发 / 补充),
  1183. * 两个回合各出一张卡片 —— 用户看到两张一模一样的卡,以为是 bug。
  1184. *
  1185. * ## 为什么回合内的去重不够
  1186. *
  1187. * `collectFiles()` 只在**单个回合**内去重。跨回合时每回合各自算出自己的文件列表,
  1188. * 同一份产物在两个回合里各出现一次。
  1189. *
  1190. * ## 做法
  1191. *
  1192. * 按「文件名 + 大小」做全局签名表,**后出现的回合**里把已出现过的文件剔掉。
  1193. * 保留最早那次 —— 那是容器第一次交付的位置,更符合「文件在这里产生」的语义。
  1194. *
  1195. * 只影响**显示**;`turn().files` 原始数据不变,对账与其他逻辑不受影响。
  1196. */
  1197. const seenFileSigs = new Set<string>();
  1198. const dedupeTurnFiles = <T extends { files?: { file: { name: string; size?: number } }[] }>(
  1199. turn: T,
  1200. ): T => {
  1201. const files = turn.files;
  1202. if (!files?.length) return turn;
  1203. const kept = files.filter((f) => {
  1204. const sig = `${f.file.name}|${f.file.size ?? 0}`;
  1205. if (seenFileSigs.has(sig)) return false;
  1206. seenFileSigs.add(sig);
  1207. return true;
  1208. });
  1209. /* 全部被去重掉 → 不新建对象(保持引用稳定,避免组件 input 变化) */
  1210. if (kept.length === files.length) return turn;
  1211. return { ...turn, files: kept } as T;
  1212. };
  1213. for (const t of turnsFromDm(
  1214. buildTurns({ messages: this.chat.messages(), typing: this.chat.peerTyping(), now }),
  1215. now,
  1216. this.chat.peerTyping(),
  1217. /* 与桌面同口径(2026-11-08):25 秒静默窗口 + 容器明确空闲时立即收尾 */
  1218. QUIET_MS,
  1219. this.chat.agentIdle(),
  1220. /* 容器结束信号(2026-11-11):`m.typing=false` 的本地接收时刻,与桌面同口径 */
  1221. this.chat.turnEndedAfter(),
  1222. )) {
  1223. /* 连发的前置提问先展示(2026-11-11,与桌面同口径) */
  1224. for (const prevAsk of t.priorAsks ?? []) {
  1225. out.push({ kind: 'msg', key: prevAsk.id, message: prevAsk });
  1226. }
  1227. if (t.userMessage) {
  1228. out.push({ kind: 'msg', key: t.userMessage.id, message: t.userMessage });
  1229. }
  1230. // 同一轮输入里的附件紧跟文字(2026-11-10,与桌面同口径)
  1231. for (const f of t.userFiles ?? []) {
  1232. out.push({ kind: 'msg', key: f.id, message: f });
  1233. }
  1234. // 已发出等待回复 / 有用户附件 也要出卡(2026-11-09 / 2026-11-10,与桌面同口径)
  1235. if (t.merged || t.live || t.userMessage || (t.userFiles?.length ?? 0) > 0) {
  1236. out.push({ kind: 'turn', key: `turn-${t.id}`, turn: dedupeTurnFiles(t) });
  1237. }
  1238. }
  1239. return out;
  1240. });
  1241. /*
  1242. * 超时未响应的全局提示(2026-11-10 用户裁决,与桌面同口径)。
  1243. *
  1244. * 🔴 不自动消失,必须用户手动关闭。
  1245. * 🔴 不只要弹一次:**当前会话只要存在超时回合,就要一直显示**;
  1246. * 条件消失(收到回复)后自动撤掉,避免残留。
  1247. */
  1248. private readonly alert = inject(AlertService);
  1249. /**
  1250. * 轻提示(2026-11-14)。
  1251. *
  1252. * 底座 `UiMToastService`:2 秒自动消失的普通提示 —— 「任务完成」正好属于
  1253. * alert.service 注释里划给它的那一类(不该用常驻的告警条,那会一直杵在屏上)。
  1254. * 容器已由 `app.ts` 全局挂载 `UiMToast`,直接注入即可。
  1255. */
  1256. /** Android 返回键接管(2026-11-15):弹层开着时返回键只关弹层 */
  1257. private readonly backBtn = inject(BackButtonService);
  1258. private static readonly TIMEOUT_TITLE = '容器长时间未响应';
  1259. private watchTurnTimeout(turns: readonly AssistantTurn[]): void {
  1260. /*
  1261. * 🔴 只看最后一轮(2026-11-10,与桌面同口径):更早的回合不论有没有回复,
  1262. * 都已经过去了,不该弹提示。
  1263. */
  1264. const last = turns[turns.length - 1];
  1265. if (!last) {
  1266. this.alert.syncState(MbChatPage.TIMEOUT_TITLE, false);
  1267. return;
  1268. }
  1269. /* 已处理过的超时 → 直接抛弃,不再判定(用户裁决 2026-11-10) */
  1270. if (this._handledTimeouts.has(last.id)) {
  1271. this.alert.syncState(MbChatPage.TIMEOUT_TITLE, false);
  1272. return;
  1273. }
  1274. const userMs = last.userMessage ? Date.parse(last.userMessage.ts) || 0 : 0;
  1275. const hasOutput = last.blocks.some((b) => b.body.length > 0 || b.steps.length > 0);
  1276. const timedOut = userMs > 0 && isTurnTimedOut(Date.now() - userMs, hasOutput, last.live);
  1277. /* 卡住检测(2026-11-11,与桌面同口径):回了一部分就停住的情况 */
  1278. const lastActivity = last.blocks.reduce((max, b) => Math.max(max, b.updatedAt), 0);
  1279. const idleMs = lastActivity > 0 ? Date.now() - lastActivity : 0;
  1280. const stalled = isTurnStalled(idleMs, hasOutput, last.live);
  1281. if (timedOut || stalled) {
  1282. this._handledTimeouts.add(last.id);
  1283. this.alert.resetDismiss(MbChatPage.TIMEOUT_TITLE);
  1284. this.alert.syncState(
  1285. MbChatPage.TIMEOUT_TITLE,
  1286. true,
  1287. stalled
  1288. ? `容器已停止响应超过 ${Math.round(STALL_MS / 1000)} 秒,任务可能已中断。可点「重新发送」把刚才的消息放回输入框。`
  1289. : `最近一条消息已超过 ${Math.round(TURN_TIMEOUT_MS / 1000)} 秒没有回复。请确认容器是否在线,或点「重新发送」重试。`,
  1290. { label: '重新发送' },
  1291. );
  1292. return;
  1293. }
  1294. this.alert.syncState(MbChatPage.TIMEOUT_TITLE, false);
  1295. }
  1296. /** 把最后一条用户消息放回输入框(2026-11-11,与桌面同口径,不自动发送) */
  1297. private resendLast(): void {
  1298. const mine = [...this.chat.messages()].reverse().find((m) => m.sender === 'me' && m.text?.trim());
  1299. if (!mine?.text) return;
  1300. this.chat.setDraft(mine.text);
  1301. this.alert.show('已放回输入框', '确认内容无误后再点发送即可。', 'warning');
  1302. }
  1303. /**
  1304. * 已处理过(提示过)的超时回合 id。
  1305. *
  1306. * 🔴 用户裁决:超时一次性处理,之后直接抛弃。
  1307. * 只存内存、不落盘 —— 落盘会跨账号串数据(用户明确否决)。
  1308. */
  1309. private readonly _handledTimeouts = new Set<string>();
  1310. /**
  1311. * 把回合内**连续的 agent 正文**合成一个块(2026-11-06 用户要求)。
  1312. *
  1313. * 容器常把一条回答拆成多条消息;此前每段各占一个块,读起来是碎片。
  1314. * 工具块、附件、失败消息各自断开,规则见 `core/message-merge.ts`。
  1315. */
  1316. /**
  1317. * 时钟计数器:每秒 +1,**只用于驱动依赖它的 computed 重算**(2026-11-10)。
  1318. *
  1319. * 与桌面端 `clockTick` 同口径。不要改成「读一个 Date.now() 快照信号」——
  1320. * 那样整页回合数据每秒重建,流式动画会被打断。
  1321. */
  1322. private readonly clockTick = signal(0);
  1323. private nowTimer: ReturnType<typeof setInterval> | null = null;
  1324. /** 回合折叠状态(用户手动切换覆盖默认) */
  1325. protected readonly title = computed(
  1326. /*
  1327. * 2026-12-02 用户裁决:标题兜底不再回落到容器名(机器 slug 不展示),
  1328. * 会话没有标题时直接显示「会话」。
  1329. */
  1330. () => this.chat.currentSession()?.title ?? '会话',
  1331. );
  1332. /**
  1333. * 标题编辑弹层开关(2026-11-23 用户要求「标题不能点击编辑」)
  1334. *
  1335. * 只在会话页开放 —— 标题来自 Matrix 房间名,改名走 m.room.name 状态事件,
  1336. * 需要房间内的 power level。改不动时给个明确提示,不静默失败。
  1337. */
  1338. protected readonly titleEditorOpen = signal(false);
  1339. protected openTitleEditor(): void {
  1340. /*
  1341. * 2026-11-23 修:原来这里有一道 `if (!roomId) return`。
  1342. * 会话目录还没刷到时 currentSession() 给的是占位对象,可能没有 roomId,
  1343. * 于是点标题完全没反应 —— 用户看到的就是「点了没动静」。
  1344. *
  1345. * 标题编辑器打开不需要 roomId,只有保存时才需要。
  1346. * 所以这里无条件打开,roomId 在保存那一刻再取。
  1347. */
  1348. this.titleEditorOpen.set(true);
  1349. }
  1350. /**
  1351. * 保存标题。
  1352. *
  1353. * 写 Matrix 房间名(`m.room.name`)—— 这是标题的权威来源,
  1354. * 本端和其他端(含其他成员的客户端)都会同步到。
  1355. * 不改本地少量副本,避免两处状态打架。
  1356. */
  1357. protected async onTitleSave(next: string): Promise<void> {
  1358. /*
  1359. * roomId 兜底(2026-11-23):占位会话可能没有 roomId,
  1360. * 但 sessionId 本身就是 Matrix 线程根、也就是房间 id 的来源。
  1361. */
  1362. const roomId = this.chat.currentSession()?.roomId ?? this.chat.sessionId();
  1363. this.titleEditorOpen.set(false);
  1364. if (!roomId) {
  1365. console.warn('[chat] 没有 roomId,无法改名');
  1366. return;
  1367. }
  1368. try {
  1369. await this.chat.renameSession(roomId, next);
  1370. } catch (e) {
  1371. /*
  1372. * 改名失败最常见的原因是权限不足(普通成员的 power level
  1373. * 改不了 m.room.name)。原来只打 console,用户完全不知道发生了什么。
  1374. */
  1375. console.warn('[chat] 标题保存失败', e);
  1376. }
  1377. }
  1378. /**
  1379. * 在**当前容器**再开一条对话(2026-11-14)。
  1380. *
  1381. * 直接复用 `/chat/:agentId/new` —— 与 m-drawer 的「新建对话」最终落到同一条
  1382. * 建房链路(`startBlankWithRoom`),不新造逻辑。
  1383. */
  1384. protected newChatInCurrent(agentId: string): void {
  1385. this.drawerOpen.set(false);
  1386. const workspaceId = this.chat.currentSession()?.workspaceId;
  1387. const scope = workspaceId ? `?ws=${encodeURIComponent(workspaceId)}` : '';
  1388. void this.router.navigateByUrl(`/mobile/chat/${encodeURIComponent(agentId)}/new${scope}`);
  1389. }
  1390. /** 从当前项目启动选数字生命流程;新会话继续沿用既有建房与归属逻辑。 */
  1391. protected startNewChatInProject(workspaceId: string | null): void {
  1392. this.drawerOpen.set(false);
  1393. this.projectPickerOpen.set(false);
  1394. this.pendingProjectId.set(workspaceId);
  1395. this.projectChatOpen.set(true);
  1396. }
  1397. protected onProjectChatOpenChange(open: boolean): void {
  1398. this.projectChatOpen.set(open);
  1399. /*
  1400. * 关闭时**不清空** pendingProjectId(2026-11-21):
  1401. * 归属现在由弹层自己的下拉维护,用户选的默认值要保留到「创建」时读取。
  1402. * 每次打开前,`startNewChatInProject` 会重新写入默认归属。
  1403. */
  1404. }
  1405. protected createProjectChat(agentId: string): void {
  1406. const workspaceId = this.pendingProjectId();
  1407. this.projectChatOpen.set(false);
  1408. this.pendingProjectId.set(null);
  1409. const scope = workspaceId ? `?ws=${encodeURIComponent(workspaceId)}` : '';
  1410. void this.router.navigateByUrl(`/mobile/chat/${encodeURIComponent(agentId)}/new${scope}`);
  1411. }
  1412. protected openProjectSession(row: { session: { id: string; agentId: string; kind?: string } }): void {
  1413. if (row.session.kind === 'group') {
  1414. void this.router.navigateByUrl(`/mobile/group/${encodeURIComponent(row.session.id)}`);
  1415. return;
  1416. }
  1417. void this.router.navigateByUrl(
  1418. `/mobile/chat/${encodeURIComponent(row.session.agentId)}/${encodeURIComponent(row.session.id)}`,
  1419. );
  1420. }
  1421. /**
  1422. * 容器名 + 状态(2026-11-11 收敛)。
  1423. *
  1424. * 与 PC 会话页头同一判据 `sessionPresence`:
  1425. * 在线/离线走 `livenessOf`,本会话是否在回复单独叠加。
  1426. * 离线时相位一律不显示(不能说明明断了还在回复)。
  1427. */
  1428. protected readonly presence = computed(() =>
  1429. this.taskPresence(this.chat.agent()),
  1430. );
  1431. /**
  1432. * 「在线 + 在干什么」的合并判定(2026-11-14)。
  1433. *
  1434. * 与桌面端 `desktop/pages/chat/chat.ts::taskLine()` 同一套口径:
  1435. * ① 本回合刚收到 ✅ 且尚未刷新 → 直接「在线」,别让顶栏还转着
  1436. * ② 容器在跑 → 用 `pulse.describe()` 的一句话任务文案
  1437. * ③ 其余交回 `sessionPresence`(离线/回复中/在线)
  1438. *
  1439. * 只在**在线且正在干活**时接管文案;离线时一律走 liveness,
  1440. * 不能因为本地还记着"刚才在跑"就瞒着用户说它在线。
  1441. */
  1442. private taskPresence(
  1443. agent: Agent | undefined,
  1444. ): { text: string; tone: SemanticTone; busy: boolean } {
  1445. const base = sessionPresence(agent, this.chat.peerTyping() ? 'replying' : undefined);
  1446. if (!base.busy && base.text === '在线' && this.chat.turnSettledLocally()) {
  1447. return { text: '在线', tone: 'success', busy: false };
  1448. }
  1449. const line = this.pulse.describe(
  1450. agent,
  1451. Date.now(),
  1452. this.chat.sessionId(),
  1453. this.chat.currentRoomId(),
  1454. this.chat.myMxId(),
  1455. );
  1456. if (!line.active) return base;
  1457. const task = this.chat.sessionTaskLine();
  1458. return {
  1459. text: task || line.text || '正在处理…',
  1460. tone: line.tone === 'neutral' ? 'info' : line.tone,
  1461. busy: true,
  1462. };
  1463. }
  1464. protected readonly subtitle = computed(() => {
  1465. const a = this.chat.agent();
  1466. if (!a) return '';
  1467. /*
  1468. * 🔴 本机断网时**优先报网络**(2026-11-16 真机实测补)。
  1469. *
  1470. * `presence()` 反映的是**容器**状态(在线/离线),跟本机网络无关。
  1471. * 断网时容器数据还是断网前那份,于是顶栏继续显示「lj-test · 在线」——
  1472. * 用户看着「在线」却发不出去消息,完全不知道为什么。
  1473. *
  1474. * 实测(小米 M2102K1AC / Android 14,飞行模式):
  1475. * 会话页顶栏一直是「在线」,没有任何断网提示。
  1476. */
  1477. /*
  1478. * 2026-12-02 用户裁决:副标题不再带容器命名(`xxx · 在线` 的 xxx 是
  1479. * 机器 slug,用户看不懂),只留在线状态本身。
  1480. */
  1481. if (this.chat.connection() === 'disconnected') {
  1482. return '网络已断开';
  1483. }
  1484. return this.presence().text;
  1485. });
  1486. /** 状态抽屉用同一个口径 */
  1487. protected readonly agentState = computed(() => {
  1488. const a = this.chat.agent();
  1489. return a ? { text: this.presence().text, tone: this.presence().tone } : null;
  1490. });
  1491. /**
  1492. * 心跳时间 → 人话(2026-11-08)。
  1493. * 原先直接渲染 ISO 原文(`2026-11-08T03:12:44.000Z`),用户在手机上没法读。
  1494. */
  1495. protected readonly heartbeatText = computed(() => {
  1496. const a = this.chat.agent();
  1497. const sec = a?.heartbeatAgeSec;
  1498. if (typeof sec === 'number' && Number.isFinite(sec)) {
  1499. if (sec < 60) return `${Math.max(0, Math.round(sec))} 秒前`;
  1500. if (sec < 3600) return `${Math.round(sec / 60)} 分钟前`;
  1501. if (sec < 86400) return `${Math.round(sec / 3600)} 小时前`;
  1502. return `${Math.round(sec / 86400)} 天前`;
  1503. }
  1504. const t = a?.heartbeatAt ? Date.parse(a.heartbeatAt) : NaN;
  1505. if (!Number.isFinite(t)) return '—';
  1506. return new Date(t).toLocaleString('zh-CN', { hour12: false });
  1507. });
  1508. /** 该会话下、该数字生命的任务(Demo 抽屉「任务」页签) */
  1509. protected readonly relatedTasks = computed<Task[]>(() => {
  1510. const id = this.chat.agentId();
  1511. return id ? this.tasksSvc.all().filter((t) => t.agentId === id) : [];
  1512. });
  1513. /** 会话内出现过的全部附件(Demo 抽屉「文件」页签) */
  1514. /**
  1515. * 「文件」页签 = 本会话里**用户自己上传的**附件(2026-11-09 与桌面同口径)。
  1516. *
  1517. * 🔴 容器产出的不算「文件」,那是「成果」—— 见 `deliverables`。
  1518. * 原来不看 sender,同一份成果在「文件」和「成果」各出现一次。
  1519. */
  1520. protected readonly files = computed(() => {
  1521. const out: NonNullable<Message['file']>[] = [];
  1522. const seen = new Set<string>();
  1523. /*
  1524. * ① 消息流里我发的附件 —— **先走这条**(2026-11-11,与桌面同口径):
  1525. * 带真实 size 与 cloudUrl,信息最全。
  1526. */
  1527. for (const m of this.chat.messages()) {
  1528. const f = m.file;
  1529. if (m.sender !== 'me' || !f) continue;
  1530. const id = fileIdentity(f.name, f.size);
  1531. if (seen.has(id)) continue;
  1532. seen.add(id);
  1533. out.push(f);
  1534. }
  1535. /*
  1536. * ② 台账里 `uploadedBy:'user'` 的记录:刷新后仍在,补上消息流翻页取不到的历史。
  1537. *
  1538. * 🔴 去重不能比 URL:台账存 S3 地址、消息流 `f.url` 是 `mxc://`,永远不等
  1539. * → 同一个文件会出现两条(用户实测)。改按「名字+大小」。
  1540. */
  1541. for (const d of this._dbUserFiles()) {
  1542. const a = d.artifacts[0];
  1543. if (!a?.url) continue;
  1544. const bytes = d.sizeBytes ?? 0;
  1545. const id = fileIdentity(a.name, bytes);
  1546. if (seen.has(id)) continue;
  1547. seen.add(id);
  1548. out.push({ kind: 'file', name: a.name, url: a.url, size: bytes > 0 ? bytes : -1, mimeType: a.type ?? '' });
  1549. }
  1550. return out;
  1551. });
  1552. /**
  1553. * 成果抽屉「成果」页签 = **本会话里容器产出的文件**(2026-11-09 与桌面同口径)。
  1554. *
  1555. * 语义分界:
  1556. * · 文件(`files`)= 我上传的
  1557. * · 成果(这里) = 容器产出的
  1558. *
  1559. * 两个来源合并去重:会话记录 `deliverableUrls` + 消息流里 agent 发的文件。
  1560. */
  1561. protected readonly deliverables = computed(() => {
  1562. const sess = this.chat.currentSession();
  1563. /* 台账已按来源分流:成果只吃「容器产出」那半边(2026-11-11) */
  1564. const fromDb = this.dbFiles();
  1565. const agentFiles = agentMessageFiles(this.chat.messages());
  1566. const fromMessages = this.deliverablesSvc.fromAgentFiles(agentFiles);
  1567. const fromRecord = this.view.bySessionUrlsOf(sess?.deliverableUrls);
  1568. return this.deliverablesSvc.merge(fromDb, fromMessages, fromRecord);
  1569. });
  1570. /**
  1571. * 按会话从数据库加载的文件(2026-11-10:与桌面端同口径)。
  1572. * 2026-11-11 起按来源分流,见 `_dbUserFiles` / `_dbFiles` 注释。
  1573. */
  1574. private readonly _dbUserFiles = signal<Deliverable[]>([]);
  1575. private readonly _dbFiles = signal<Deliverable[]>([]);
  1576. readonly dbFiles = this._dbFiles.asReadonly();
  1577. /** 拉当前会话的文件台账;会话切换时重跑 */
  1578. /**
  1579. * 把 agent 消息里的容器产出链接补登进台账(2026-11-13)。
  1580. *
  1581. * 与桌面端 `DkChatPage.bindAgentFiles` 同口径:归属键用 roomId,
  1582. * 缺 roomId 就跳过(宁可少补也不归错)。
  1583. */
  1584. private bindAgentFiles(sessionId: string): void {
  1585. const roomId = this.chat.currentSession()?.roomId;
  1586. if (!roomId) return;
  1587. const urls = agentMessageFiles(this.chat.messages()).map((file) => file.url);
  1588. if (urls.length === 0) return;
  1589. void this.fileBinding.bindPending(roomId, sessionId, urls);
  1590. }
  1591. private loadSessionFiles(): void {
  1592. const sid = this.chat.currentSession()?.id;
  1593. if (!sid) {
  1594. this._dbUserFiles.set([]);
  1595. this._dbFiles.set([]);
  1596. return;
  1597. }
  1598. void this.deliverablesSvc
  1599. .loadSplitForSession(sid)
  1600. .then(({ userFiles, agentFiles }) => {
  1601. if (this.chat.currentSession()?.id !== sid) return;
  1602. /* 内容没变就不写新数组(2026-11-13 请求风暴第二道防线,与桌面端同口径) */
  1603. if (!sameDeliverableIds(this._dbUserFiles(), userFiles)) this._dbUserFiles.set(userFiles);
  1604. if (!sameDeliverableIds(this._dbFiles(), agentFiles)) this._dbFiles.set(agentFiles);
  1605. })
  1606. .catch(() => {
  1607. if (this.chat.currentSession()?.id === sid) {
  1608. if (this._dbUserFiles().length > 0) this._dbUserFiles.set([]);
  1609. if (this._dbFiles().length > 0) this._dbFiles.set([]);
  1610. }
  1611. });
  1612. }
  1613. /**
  1614. * 🔴 同会话内的台账重拉去抖(2026-11-24 请求风暴第三道防线,
  1615. * 与桌面端 `DkChatPage.scheduleSessionFilesReload` 同口径)。
  1616. *
  1617. * 下面的 effect 依赖 `messages().length`,Matrix 首次同步回放时它连续变化,
  1618. * 旧实现每次都发一次无缓存的 `fetchFilesBySession` —— 实测 45 秒 710 个请求。
  1619. * 口径:**切会话立即拉**(用户等着看成果区),**同会话消息变化去抖 2s 尾随拉一次**。
  1620. */
  1621. private filesReloadTimer: ReturnType<typeof setTimeout> | null = null;
  1622. private lastFilesSid = '';
  1623. private static readonly FILES_RELOAD_DEBOUNCE_MS = 2000;
  1624. private scheduleSessionFilesReload(sid: string | undefined): void {
  1625. if (this.filesReloadTimer) {
  1626. clearTimeout(this.filesReloadTimer);
  1627. this.filesReloadTimer = null;
  1628. }
  1629. if ((sid ?? '') !== this.lastFilesSid) {
  1630. this.lastFilesSid = sid ?? '';
  1631. this.loadSessionFiles();
  1632. return;
  1633. }
  1634. this.filesReloadTimer = setTimeout(() => {
  1635. this.filesReloadTimer = null;
  1636. this.loadSessionFiles();
  1637. }, MbChatPage.FILES_RELOAD_DEBOUNCE_MS);
  1638. }
  1639. /** 有多少成果附件还没上云(与桌面 `session-rail` 同口径) */
  1640. protected readonly notOnCloudCount = computed(() =>
  1641. this.deliverables().reduce((n, d) => n + d.artifacts.filter((a) => !a.url).length, 0),
  1642. );
  1643. private readonly scroller = viewChild<ElementRef<HTMLDivElement>>('scroller');
  1644. /** 用户是否停在底部附近(不在底部时不自动滚动,避免打断向上翻历史) */
  1645. private stickBottom = true;
  1646. /**
  1647. * 用户是否**主动**上翻离开了底部(2026-11-10,与桌面端 `userScrolledAway` 同口径)。
  1648. *
  1649. * 🔴 为什么 `stickBottom` 不够:
  1650. * `stickBottom` 只记「此刻离底部多远」,而程序滚动本身也会触发 scroll 事件 ——
  1651. * 用户上翻 → 新消息到达把列表拉回底部 → scroll 事件又把 `stickBottom` 置回 true →
  1652. * 下一次新消息继续拉回。形成「上翻 → 被拽回 → 再也翻不上去」的死循环
  1653. * (两轮回复交替到达时最明显,用户实测)。
  1654. * 这里单独记「用户是不是主动走的」,且只在**用户自己滚动**时改变。
  1655. */
  1656. private userScrolledAway = false;
  1657. /** 正在加载更早消息(防重入 + 分页期间不贴底) */
  1658. private loadingEarlier = false;
  1659. /** 上次贴底的时刻(节流用) */
  1660. private lastStickAt = 0;
  1661. protected retryMessage(id: string): void {
  1662. void this.chat.retry(id);
  1663. }
  1664. constructor() {
  1665. effect(() => {
  1666. const transfer = this.incomingShares.transfer();
  1667. const state = this.chat.state();
  1668. const ready = state === 'ready' || state === 'empty';
  1669. const agentId = this.chat.agentId();
  1670. const sessionId = this.chat.sessionId();
  1671. if (transfer && ready && agentId === transfer.agentId && sessionId === transfer.sessionId) {
  1672. untracked(() => void this.incomingShares.stageInto(this.chat));
  1673. } else if (transfer && state === 'error' && agentId === transfer.agentId) {
  1674. untracked(() => this.incomingShares.cancelTransfer(this.chat.error() || '会话打开失败,请重试'));
  1675. }
  1676. });
  1677. /* 提示条「重新发送」(2026-11-11,与桌面同口径) */
  1678. this.alert.onAction((a) => {
  1679. if (a.title === MbChatPage.TIMEOUT_TITLE) this.resendLast();
  1680. });
  1681. /*
  1682. * Android 返回键接管(2026-11-15 真机问题修复)
  1683. *
  1684. * 🔴 不接管时的实测症状(两个,同一根因):
  1685. * ① 打开文件预览后按返回 → 预览关掉的**同时会话也退出到列表**(退两层)
  1686. * ② 偶发整屏白屏、15 秒不恢复,只能杀进程
  1687. * 原因:弹层是组件内部状态,浏览器历史里没有对应记录,
  1688. * 系统把返回键当「浏览器后退」,退掉的是上一个**路由**。
  1689. *
  1690. * 这里登记一个关闭器:只要有任一弹层开着,返回键只关弹层,不碰路由。
  1691. * 后进先出 —— 用户看到的最上层先关。
  1692. */
  1693. effect((onCleanup) => {
  1694. const anyOpen =
  1695. this.drawerOpen() ||
  1696. this.projectPickerOpen() ||
  1697. this.projectChatOpen() ||
  1698. this.sheetOpen() ||
  1699. !!this.lightbox() ||
  1700. !!this.preview();
  1701. if (!anyOpen) return;
  1702. this.backBtn.register('mobile-chat-overlays', () => {
  1703. if (this.drawerOpen()) {
  1704. this.drawerOpen.set(false);
  1705. return true;
  1706. }
  1707. if (this.projectChatOpen()) {
  1708. this.onProjectChatOpenChange(false);
  1709. return true;
  1710. }
  1711. if (this.projectPickerOpen()) {
  1712. this.projectPickerOpen.set(false);
  1713. return true;
  1714. }
  1715. if (this.sheetOpen()) {
  1716. this.sheetOpen.set(false);
  1717. return true;
  1718. }
  1719. if (this.lightbox()) {
  1720. this.lightbox.set(null);
  1721. return true;
  1722. }
  1723. if (this.preview()) {
  1724. this.preview.set(null);
  1725. return true;
  1726. }
  1727. return false;
  1728. });
  1729. onCleanup(() => this.backBtn.unregister('mobile-chat-overlays'));
  1730. });
  1731. // 完成提醒由根部 TaskCompletionNotificationService 统一监听。
  1732. /*
  1733. * 右侧栏:会话切换或消息数变化时重拉文件台账(2026-11-10,与桌面端同口径)。
  1734. * 容器产出的文件要等登记完才进台账,回合结束消息数变化正好触发刷新。
  1735. */
  1736. effect(() => {
  1737. const sid = this.chat.currentSession()?.id;
  1738. const count = this.chat.messages().length;
  1739. /*
  1740. * 🔴 `untracked` 必须加(2026-11-13 请求风暴修复,与桌面端同因)。
  1741. *
  1742. * `loadSessionFiles()` 内部会写 `_dbUserFiles` / `_dbAgentFiles`(新数组),
  1743. * 而这些信号又被本 effect 的依赖链读到 —— 不隔离就会自我唤醒,
  1744. * 实测 16.9 秒 418 个 `POST /api/functions`。
  1745. *
  1746. * 🔴 台账重拉还要去抖(2026-11-24,与桌面端同口径):
  1747. * untracked 防自我唤醒,防不了回放期间 count 连续变化。
  1748. */
  1749. untracked(() => {
  1750. this.scheduleSessionFilesReload(sid);
  1751. /* 成果绑定兜底(2026-11-13,与桌面端同口径) */
  1752. if (sid && count > 0) this.bindAgentFiles(sid);
  1753. });
  1754. });
  1755. // 路由参数 → 打开会话;参数变化时重开
  1756. this.route.paramMap.subscribe((pm) => {
  1757. const agentId = pm.get('id');
  1758. if (!agentId) return;
  1759. const sid = pm.get('sessionId') ?? undefined;
  1760. void this.openSession(agentId, sid);
  1761. void this.tasksSvc.ensureAllLoaded();
  1762. });
  1763. // 新消息到达:贴底时滚到底(用户主动上翻期间不打扰,2026-11-10)
  1764. effect(() => {
  1765. this.chat.messages();
  1766. if (this.loadingEarlier) return;
  1767. if (this.stickBottom && !this.userScrolledAway) this.stickToBottom();
  1768. });
  1769. // 有活着的回合时才跑每秒时钟(见 `syncClock` 注释)
  1770. effect(() => {
  1771. this.aiRows();
  1772. untracked(() => this.syncClock());
  1773. });
  1774. /*
  1775. * 超时未响应 → 全局提示(2026-11-10,A2 重构,与桌面同口径)。
  1776. *
  1777. * 🔴 不再依赖 `now`。
  1778. * 每秒时钟在「没有任何 live 回合」时停表,而超时恰恰发生在 live
  1779. * 已变 false 之后 → 判定永远跑不到 → 提示不弹。
  1780. * 现在只在这里同步看门狗开关,周期判定交给独立 interval。
  1781. */
  1782. effect(() => {
  1783. this.aiRows();
  1784. untracked(() => this.syncTimeoutWatch());
  1785. });
  1786. }
  1787. ngOnDestroy(): void {
  1788. // 离开会话不 close:Matrix 连接与未读计数需要保持(与桌面一致)
  1789. if (this.nowTimer !== null) {
  1790. clearInterval(this.nowTimer);
  1791. this.nowTimer = null;
  1792. }
  1793. this.stopTimeoutWatch();
  1794. // 去抖中的台账重拉也要清掉(2026-11-24 去抖引入,与桌面端同口径)
  1795. if (this.filesReloadTimer) {
  1796. clearTimeout(this.filesReloadTimer);
  1797. this.filesReloadTimer = null;
  1798. }
  1799. }
  1800. /*
  1801. * 超时看门狗(2026-11-10,A2)。
  1802. * 与 `syncClock` 分开:后者随 live 停表,前者只看「有无未回复的回合」。
  1803. */
  1804. private timeoutHandle: ReturnType<typeof setInterval> | null = null;
  1805. private syncTimeoutWatch(): void {
  1806. const waiting = this.hasPendingTurn();
  1807. if (waiting && this.timeoutHandle === null) {
  1808. this.timeoutHandle = setInterval(() => {
  1809. this.evaluateTimeout();
  1810. if (!this.hasPendingTurn()) this.stopTimeoutWatch();
  1811. }, 5000);
  1812. this.evaluateTimeout();
  1813. } else if (!waiting && this.timeoutHandle !== null) {
  1814. this.stopTimeoutWatch();
  1815. }
  1816. }
  1817. private stopTimeoutWatch(): void {
  1818. if (this.timeoutHandle !== null) {
  1819. clearInterval(this.timeoutHandle);
  1820. this.timeoutHandle = null;
  1821. }
  1822. }
  1823. /** 是否存在「已发出、容器还没有任何输出」的回合(与 live 无关) */
  1824. private hasPendingTurn(): boolean {
  1825. /*
  1826. * 🔴 2026-11-10 用户裁决:超时即终态,之后直接抛弃,不再监听。
  1827. *
  1828. * 只在「距发出还没超过超时窗口 + 10 秒」时才盯着。
  1829. * 刷新页面时老消息早已超出窗口 → 看门狗不会启动 → 不会再弹。
  1830. */
  1831. const now = Date.now();
  1832. return this.aiRows().some((r) => {
  1833. if (r.kind !== 'turn') return false;
  1834. const t = r.turn;
  1835. if (!t.userMessage) return false;
  1836. if (this._handledTimeouts.has(t.id)) return false;
  1837. const userMs = Date.parse(t.userMessage.ts) || 0;
  1838. if (!userMs) return false;
  1839. if (now - userMs >= TURN_TIMEOUT_MS + 10_000) return false;
  1840. return !t.blocks.some((b) => b.body.length > 0 || b.steps.length > 0);
  1841. });
  1842. }
  1843. private evaluateTimeout(): void {
  1844. const turns = this.aiRows().filter((r) => r.kind === 'turn').map((r) => r.turn);
  1845. this.watchTurnTimeout(turns);
  1846. }
  1847. /*
  1848. * 🔴 时钟驱动(2026-11-09,C2)。
  1849. *
  1850. * `now` signal 原先只有声明、没有任何地方 set —— `aiRows` 只在
  1851. * `messages()` / `peerTyping()` 变化时重算。容器若一直报 typing、
  1852. * 又不再发新消息,回合的「25 秒静默」永远等不到,卡片会一直挂在
  1853. * 「正在输出…」(用户实测 163 秒)。
  1854. *
  1855. * 每秒推进一次 `now`,让静默判定真正随时间走。只在有活着的回合时起表,
  1856. * 空闲页面不白跑定时器;离页即清。
  1857. */
  1858. private syncClock(): void {
  1859. const needsTick = this.aiRows().some((r) => r.kind === 'turn' && r.turn.live);
  1860. if (needsTick && this.nowTimer === null) {
  1861. this.nowTimer = setInterval(() => {
  1862. this.clockTick.update((n) => n + 1);
  1863. if (!this.aiRows().some((r) => r.kind === 'turn' && r.turn.live)) {
  1864. if (this.nowTimer !== null) clearInterval(this.nowTimer);
  1865. this.nowTimer = null;
  1866. }
  1867. }, 1000);
  1868. } else if (!needsTick && this.nowTimer !== null) {
  1869. clearInterval(this.nowTimer);
  1870. this.nowTimer = null;
  1871. }
  1872. }
  1873. /**
  1874. * 打开会话;`sessionId === 'new'` 为「新建对话」入口(与桌面 `/chat/:id/new` 同口径)。
  1875. *
  1876. * 🔴 建出会话后立刻 replaceUrl 成真实会话地址,避免刷新回到 `new`;
  1877. * 这里**不调用 pruneEmpty**(桌面为此踩过坑:刚建的空会话被当成空壳删掉)。
  1878. */
  1879. private async openSession(agentId: string, sessionId?: string): Promise<void> {
  1880. if (sessionId === 'new') {
  1881. const ws = this.route.snapshot.queryParamMap.get('ws');
  1882. /* 一房间一会话:建房完成后再进入(2026-11-12,与桌面端同口径) */
  1883. this.preparingRoom.set(true);
  1884. let created: Awaited<ReturnType<typeof this.chat.startBlankWithRoom>> = null;
  1885. try {
  1886. created = await this.chat.startBlankWithRoom(agentId, ws || null);
  1887. } finally {
  1888. this.preparingRoom.set(false);
  1889. }
  1890. if (created) {
  1891. /*
  1892. * 首页输入坞带过来的草稿(2026-11-09):用户先在首页打字、再选人,
  1893. * 字不能丢。取回后立刻清掉,避免下次新建时又冒出来。
  1894. */
  1895. const carryKey = PENDING_DRAFT_KEY(agentId);
  1896. const carried = sessionStorage.getItem(carryKey);
  1897. if (carried) {
  1898. sessionStorage.removeItem(carryKey);
  1899. this.chat.setDraft(carried);
  1900. }
  1901. void this.router.navigateByUrl(
  1902. `/mobile/chat/${agentId}/${encodeURIComponent(created.id)}`,
  1903. { replaceUrl: true },
  1904. );
  1905. return;
  1906. }
  1907. } else {
  1908. await this.chat.open(agentId, sessionId);
  1909. this.sessionsSvc.pruneEmpty(this.chat.sessionId() ?? undefined);
  1910. }
  1911. this.stickBottom = true;
  1912. this.userScrolledAway = false;
  1913. this.lastStickAt = 0;
  1914. queueMicrotask(() => this.scrollToBottom());
  1915. void this.fillViewportIfNeeded();
  1916. }
  1917. protected send(text: string): void {
  1918. /*
  1919. * 自己发消息 = 明确想看结果 → 解除「用户上翻」保护并直接贴底。
  1920. * 否则用户之前上翻过、发给新消息后还停在半空,看不到自己的消息和目标容器状态。
  1921. */
  1922. this.userScrolledAway = false;
  1923. this.stickBottom = true;
  1924. this.lastStickAt = 0;
  1925. void this.chat.sendText(text);
  1926. this.stickToBottom();
  1927. }
  1928. protected retry(): void {
  1929. const agentId = this.route.snapshot.paramMap.get('id');
  1930. const sid = this.route.snapshot.paramMap.get('sessionId') ?? undefined;
  1931. if (agentId) void this.chat.open(agentId, sid, true);
  1932. }
  1933. protected reconnect(): void {
  1934. this.retry();
  1935. }
  1936. /** 下拉刷新回调:强制重开当前会话(retry 已是 force 语义),等一拍让状态落地 */
  1937. protected readonly onPullRefresh = (): Promise<void> => {
  1938. this.reconnect();
  1939. return new Promise((r) => setTimeout(r, 600));
  1940. };
  1941. protected loadMore(): void {
  1942. void this.loadEarlier();
  1943. }
  1944. /**
  1945. * 滚动处理:
  1946. * ① 更新「是否贴底」(新消息到达时决定要不要自动滚到底)
  1947. * ② **触顶自动加载更早消息**(与 PC 端 `desktop/pages/chat/chat.ts` 同口径)
  1948. */
  1949. protected onScroll(e: Event): void {
  1950. const el = e.target as HTMLElement;
  1951. const gap = el.scrollHeight - el.scrollTop - el.clientHeight;
  1952. this.stickBottom = gap < 80;
  1953. /*
  1954. * 用户上翻的判定阈值比贴底恢复的阈值大(与桌面端 160px 同口径):
  1955. * 只有明显离开底部才算「主动走开」,避免图片异步加载把高度撑大后误判。
  1956. * 滚回接近底部时自动恢复贴底。
  1957. */
  1958. this.userScrolledAway = gap > 160;
  1959. if (el.scrollTop > TOP_LOAD_PX) return;
  1960. if (this.loadingEarlier || this.chat.paginating() || !this.chat.hasMoreHistory()) return;
  1961. void this.loadEarlier();
  1962. }
  1963. /**
  1964. * 加载更早的消息,并**保持视口位置不变**。
  1965. *
  1966. * 🔴 不做补偿的话,分页插入后 `scrollTop` 仍是原值,
  1967. * 用户眼前的内容会整体往下窜(PC 端早期踩过,见 desktop chat.ts:2921-2940)。
  1968. *
  1969. * 做法与 PC 一致:记下加载前的 scrollHeight / scrollTop,等两帧让新内容完成布局,
  1970. * 再把 scrollTop 加上新增的高度差。
  1971. */
  1972. private async loadEarlier(): Promise<void> {
  1973. if (this.loadingEarlier) return;
  1974. const el = this.scroller()?.nativeElement;
  1975. if (!el || !this.chat.hasMoreHistory()) return;
  1976. this.loadingEarlier = true;
  1977. const beforeHeight = el.scrollHeight;
  1978. const beforeTop = el.scrollTop;
  1979. try {
  1980. await this.chat.paginate();
  1981. // 等两帧:一帧提交 DOM、一帧完成布局(图片/表格撑高)
  1982. await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(null))));
  1983. const after = this.scroller()?.nativeElement;
  1984. if (after) {
  1985. after.scrollTop = beforeTop + (after.scrollHeight - beforeHeight);
  1986. }
  1987. } finally {
  1988. this.loadingEarlier = false;
  1989. }
  1990. }
  1991. /**
  1992. * 首屏不满一屏且还有更早消息时自动补齐(最多 3 轮)。
  1993. * 否则用户看到内容没填满、却没有可滚动空间,永远触发不到「触顶加载」。
  1994. *
  1995. * 🔴 新建态不补齐(2026-11-08):新建会话本来就没有更早的消息,
  1996. * 而 `hasMoreHistory` 取自房间级 token —— 不挡就会自动翻出整个房间的旧历史。
  1997. */
  1998. private async fillViewportIfNeeded(): Promise<void> {
  1999. if (this.chat.state() === 'empty') return;
  2000. for (let i = 0; i < 3; i++) {
  2001. const el = this.scroller()?.nativeElement;
  2002. if (!el || !this.chat.hasMoreHistory()) return;
  2003. if (el.scrollHeight > el.clientHeight + 8) return;
  2004. await this.loadEarlier();
  2005. }
  2006. }
  2007. protected back(): void {
  2008. void this.router.navigateByUrl('/mobile/messages');
  2009. }
  2010. /**
  2011. * 任务深链(2026-11-11 改)。
  2012. *
  2013. * 「任务」页路由已下线(用户裁决:入口和路由一起关),原来跳
  2014. * `/mobile/tasks/:id` 会落到消息列表,用户以为点坏了。
  2015. * 改为**留在当前页**:关掉抽屉、打开成果/状态抽屉的任务页,并高亮该条。
  2016. */
  2017. protected goTask(id: string): void {
  2018. this.sheetTab.set('task');
  2019. this.railHighlight.set(id);
  2020. this.sheetOpen.set(true);
  2021. if (this.railHighlightTimer) clearTimeout(this.railHighlightTimer);
  2022. this.railHighlightTimer = setTimeout(() => this.railHighlight.set(null), 2000);
  2023. }
  2024. /** 试用到期提示条的「去开通」:回套餐页(2026-12-03) */
  2025. protected goPlan(): void {
  2026. void this.router.navigateByUrl('/plans');
  2027. }
  2028. /**
  2029. * 打开文件预览(2026-11-03)。
  2030. *
  2031. * 与 PC 端 `openFile()` 同口径:按类型分流 —— 图片进灯箱,其余进通用预览器。
  2032. * 原实现用 `window.open` 新开标签页,移动端体验割裂(离开 App、失去返回路径)。
  2033. */
  2034. protected openFile(f: {
  2035. name: string;
  2036. url?: string;
  2037. cloudUrl?: string;
  2038. mimeType?: string;
  2039. size?: number;
  2040. }): void {
  2041. /*
  2042. * 🔴 优先用云盘链接(2026-11-13 用户实测反馈):
  2043. * `url` 可能是本地 blob(刷新即失效)或 Matrix 媒体地址(需要 blob 中转、
  2044. * Safari 兼容差);`cloudUrl` 才是长期可访问、能直接打开的云盘链接。
  2045. */
  2046. const url = f.cloudUrl || f.url;
  2047. if (!url) return;
  2048. const mime = f.mimeType ?? '';
  2049. if (previewKindOf(f.name || url, mime) === 'image') {
  2050. this.lightbox.set({ url, name: f.name, size: f.size ?? 0 });
  2051. return;
  2052. }
  2053. this.preview.set({ url, name: f.name, mimeType: mime });
  2054. }
  2055. protected taskTone(t: Task): BadgeTone {
  2056. return TASK_TONE[t.status] ?? 'neutral';
  2057. }
  2058. protected taskText(t: Task): string {
  2059. return TASK_STATUS_TEXT[t.status] ?? t.status;
  2060. }
  2061. private scrollToBottom(): void {
  2062. const el = this.scroller()?.nativeElement;
  2063. if (el) el.scrollTop = el.scrollHeight;
  2064. }
  2065. /**
  2066. * 贴底(2026-11-10,与桌面端 `stickToBottom` 同口径)。
  2067. *
  2068. * · 用户主动上翻 → 不拽回
  2069. * · 正在加载更早消息 → 不贴底(那是往上插入)
  2070. * · 200ms 节流:流式输出时每帧都在长高,不节流会和渲染抢主线程
  2071. * · 补一次 rAF + 一次延时:图片 / Markdown 异步渲染后高度还会变
  2072. */
  2073. private stickToBottom(): void {
  2074. if (this.userScrolledAway) return;
  2075. if (this.loadingEarlier) return;
  2076. const now = Date.now();
  2077. if (now - this.lastStickAt < 200) return;
  2078. this.lastStickAt = now;
  2079. queueMicrotask(() => this.scrollToBottom());
  2080. requestAnimationFrame(() => {
  2081. this.scrollToBottom();
  2082. setTimeout(() => this.scrollToBottom(), 120);
  2083. });
  2084. }
  2085. }
  2086. /** 渲染行的时间戳(用于按时间排序) */
  2087. function keyTs(r: MessageRow): number {
  2088. const ts = (m?: Message): number => (m ? Date.parse(m.ts) || 0 : 0);
  2089. if (r.kind === 'msg') return ts(r.message);
  2090. if (r.kind === 'turn') {
  2091. for (const b of r.blocks) {
  2092. if (b.kind === 'msg') return ts(b.message);
  2093. }
  2094. }
  2095. return 0;
  2096. }
  2097. /**
  2098. * 两组成果的 id 序列是否完全相同(2026-11-13 请求风暴防线)。
  2099. *
  2100. * 与桌面端 `sameIds` 同口径:内容没变就不写新数组,
  2101. * 避免无意义唤醒下游 computed / effect。
  2102. */
  2103. function sameDeliverableIds(
  2104. a: readonly Deliverable[],
  2105. b: readonly Deliverable[],
  2106. ): boolean {
  2107. if (a.length !== b.length) return false;
  2108. for (let i = 0; i < a.length; i++) if (a[i].id !== b[i].id) return false;
  2109. return true;
  2110. }