| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209 |
- import { UserNoticePipe } from '../../../components/feedback/user-notice.pipe';
- import {
- ChangeDetectionStrategy,
- Component,
- ElementRef,
- OnDestroy,
- computed,
- effect,
- inject,
- signal,
- untracked,
- viewChild,
- } from '@angular/core';
- import { ActivatedRoute, Router } from '@angular/router';
- import { MAppBarComponent } from '../../components/m-app-bar/m-app-bar';
- import { MDockComponent } from '../../components/m-dock/m-dock';
- import { MDrawerComponent } from '../../components/m-drawer/m-drawer';
- import { MNewChatSheetComponent } from '../../components/m-new-chat/m-new-chat';
- import { MProjectSwitcherComponent } from '../../components/m-project-switcher/m-project-switcher';
- import { TitleEditorComponent } from '../../components/m-title-editor/m-title-editor';
- import { MEmptyComponent } from '../../components/m-empty/m-empty';
- import { MMsgComponent } from '../../components/m-msg/m-msg';
- import { FilePreviewComponent } from '../../../components/preview/file-preview/file-preview';
- import { ImageLightboxComponent } from '../../../components/preview/image-lightbox/image-lightbox';
- import { previewKindOf } from '../../../components/preview/file-kind';
- import { LockScrollDirective } from '../../directives/lock-scroll.directive';
- import { BadgeTone, MBadgeComponent, TASK_TONE, TASK_STATUS_TEXT } from '../../components/m-badge/m-badge';
- import { ChatService } from '../../../core/chat.service';
- import { ShareReceiveService } from '../../../core/share-receive.service';
- import { PENDING_DRAFT_KEY } from '../home/home';
- import { LoopGuardService } from '../../../core/loop-guard.service';
- import { Agent, Deliverable, SemanticTone, Task } from '../../../core/api/models';
- import { ChatSessionService } from '../../../core/chat-session.service';
- import { TasksService } from '../../../core/tasks.service';
- import { fmtSize } from '../../../core/format';
- import { MobileChatViewService } from '../../../core/mobile-chat-view.service';
- import { DeliverablesService } from '../../../core/deliverables.service';
- import { AgentFileBindingService } from '../../../core/agent-file-binding.service';
- import { agentMessageFiles } from '../../../core/message-files';
- import { buildTurns, QUIET_MS } from '../../../core/turn-aggregator';
- import {
- Block,
- isToolActivityMessage,
- toolActivitySummary,
- } from '../../../core/message-segments';
- import { Message } from '../../../core/api/models';
- import { sessionPresence } from '../../../core/agent-liveness';
- import { TaskPulseService } from '../../../core/task-pulse.service';
- import { BackButtonService } from '../../../core/back-button.service';
- import { fileIdentity } from '../../../core/s3-link';
- import { mergeConsecutiveBodies } from '../../../core/message-merge';
- import {
- AssistantTurn,
- isTurnStalled,
- isTurnTimedOut,
- STALL_MS,
- TURN_TIMEOUT_MS,
- turnsFromDm,
- } from '../../../core/assistant-turn';
- import { AlertService } from '../../../core/alert.service';
- import { AssistantTurnComponent } from '../../../components/domain/assistant-turn/assistant-turn';
- import { UiMPullRefresh } from '../../../ui/mobile/components/pull-refresh/pull-refresh';
- /**
- * 会话消息行:普通消息 or 已合并的终端活动组。
- * 与桌面端 `desktop/pages/chat/chat.ts` 的 `MessageRow` 同构。
- */
- /** 触顶阈值:滚动到距顶部 80px 内即自动加载更早消息(与 PC 一致) */
- const TOP_LOAD_PX = 80;
- type MessageRow =
- | { kind: 'msg'; key: string; message: Message }
- | { kind: 'tool'; key: string; block: Extract<Block, { kind: 'process' }> }
- /** 回合:一次提问的全部 agent 输出合成一条气泡(2026-11-05) */
- | {
- kind: 'turn';
- key: string;
- blocks: TurnBlock[];
- open: boolean;
- collapsed: boolean;
- seconds: number;
- };
- /** 卡片渲染行(2026-11-07):用户消息一行,AI 一整轮一张卡 */
- type AiRow =
- | { kind: 'msg'; key: string; message: Message }
- | { kind: 'turn'; key: string; turn: AssistantTurn };
- /** 回合内部的一块:正文一条,或一组工具执行过程 */
- type TurnBlock =
- | { kind: 'msg'; key: string; message: Message }
- | { kind: 'tool'; key: string; block: Extract<Block, { kind: 'process' }> };
- type SheetTab = 'task' | 'file' | 'deliver' | 'state';
- /**
- * 会话详情(Demo 06 + 07 成果抽屉)
- *
- * 全屏路由(无 TabBar):顶栏固定 + 消息区独立滚动 + 底部输入坞固定。
- * 所有收发状态来自 `ChatService`(与桌面同一状态机),本页只做编排:
- * · `:id` = agentId;`:sessionId` 缺省 = 打开该容器最近一条会话
- * · 无 sessionId 且容器下没有会话 → `startBlank()` 建一条「新建对话」
- */
- @Component({
- selector: 'app-mb-chat-page',
- changeDetection: ChangeDetectionStrategy.OnPush,
- imports: [UserNoticePipe,
- MAppBarComponent,
- MDockComponent,
- MDrawerComponent,
- MNewChatSheetComponent,
- MProjectSwitcherComponent,
- TitleEditorComponent,
- MEmptyComponent,
- MMsgComponent,
- MBadgeComponent,
- FilePreviewComponent,
- ImageLightboxComponent,
- LockScrollDirective,
- AssistantTurnComponent,
- UiMPullRefresh,
- ],
- template: `
- <div class="m-page m-page--fixed">
- <app-m-app-bar
- [title]="title()"
- [subtitle]="subtitle()"
- [back]="true"
- [rightCount]="2"
- [titleEditable]="true"
- (backTap)="back()"
- (titleTap)="openTitleEditor()"
- >
- <!--
- 会话切换(2026-11-09):抽屉组件早就引入了却没用,导致移动端进了
- 一条会话就出不去 —— 只能退回消息列表再进,等于不能切会话。
- -->
- <button barRight type="button" class="m-fab" aria-label="切换会话" (click)="drawerOpen.set(true)">
- <i class="fa-solid fa-bars-staggered" aria-hidden="true"></i>
- </button>
- <button barRight type="button" class="m-fab" aria-label="查看成果与状态" (click)="sheetOpen.set(true)">
- <i class="fa-solid fa-folder-open" aria-hidden="true"></i>
- </button>
- </app-m-app-bar>
- <app-m-drawer
- [open]="drawerOpen()"
- [activeSessionId]="chat.sessionId()"
- [quickNewAgentId]="chat.agent()?.id ?? null"
- (close)="drawerOpen.set(false)"
- (newChat)="startNewChatInProject(chat.currentSession()?.workspaceId ?? null)"
- (newChatWithWs)="startNewChatInProject($event)"
- (quickNew)="newChatInCurrent($event)"
- />
- <!-- 试用到期(2026-12-03):门禁已拦,深链直达时也给明确原因 -->
- @if (chat.agent()?.trialExpired) {
- <div class="trial-expired-bar" role="alert">
- <i class="fa-solid fa-hourglass-end" aria-hidden="true"></i>
- <span>两天试用已到期,开通套餐后继续使用</span>
- <button type="button" class="trial-expired-btn" (click)="goPlan()">去开通</button>
- </div>
- }
- @if (chat.connection() === 'disconnected' && chat.state() !== 'loading') {
- <button type="button" class="m-conn-bar" (click)="reconnect()">
- <i class="fa-solid fa-plug-circle-exclamation" aria-hidden="true"></i>
- 连接已断开,点击重连
- </button>
- }
- <!--
- 回环提示(2026-11-09):桌面早就有,移动端一直没有 ——
- 手机上看不到「为什么没回复」,只会一脸茫然。
- -->
- @if (loop.paused()) {
- <div class="m-loop-bar" role="status">
- <div class="m-loop-text">
- <i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i>
- <span>检测到自动对话循环,已暂停:{{ loop.pauseDetail() }}</span>
- </div>
- <button type="button" class="m-loop-act" (click)="loop.resume()">继续协作</button>
- </div>
- }
- <div class="m-chat-body" #scroller (scroll)="onScroll($event)">
- <!-- 下拉刷新(2026-12-02 用户裁决:主要页面都要):强制重开当前会话 -->
- <ui-m-pull-refresh [onRefresh]="onPullRefresh">
- @switch (chat.state()) {
- @case ('loading') {
- <div class="m-loading" aria-busy="true" aria-label="正在加载消息">
- <span class="m-typing"><i></i><i></i><i></i></span>
- </div>
- }
- @case ('error') {
- <app-m-empty
- icon="fa-solid fa-triangle-exclamation"
- title="消息加载失败"
- [description]="(chat.error() ?? '') | userNotice"
- [retryable]="true"
- (retry)="reconnect()"
- />
- }
- @case ('empty') {
- @if (preparingRoom()) {
- <!-- 新建会话建房间中(2026-11-13):给出明确反馈,避免「点了没反应」 -->
- <div class="m-loading" role="status" aria-live="polite" aria-label="正在准备会话">
- <span class="m-typing"><i></i><i></i><i></i></span>
- <p class="m-loading-text">正在准备会话…</p>
- </div>
- } @else if (chat.emptyReason() === 'removed') {
- <!-- 已软删会话(2026-11-09 用户裁决):URL 直达也不认领 -->
- <app-m-empty
- icon="fa-solid fa-trash-can"
- title="该会话已删除"
- description="这条对话已经被删除,无法再查看或继续发送消息。"
- />
- } @else if (chat.emptyReason() === 'blank') {
- <!--
- 空壳会话(2026-11-12):已翻到房间最早、目录里有这条、但一条消息都没有。
- 必须与「暂时取不到」分开说,否则用户会一直等、以为数据丢了。
- -->
- <app-m-empty
- icon="fa-solid fa-inbox"
- title="这条对话没有保存任何消息"
- description="会话记录还在,但服务器上找不到它的任何消息内容。"
- />
- } @else if (chat.emptyReason() === 'unloaded') {
- <!--
- 有会话但历史取不到(2026-11-09):不能伪装成「开始新的对话」。
- 🔴 2026-11-13 补「重试」(真机实测):移动网络下回溯请求可能失败,
- 原先没有重试入口,用户只能一直看着这句话。
- -->
- <app-m-empty
- icon="fa-solid fa-inbox"
- title="这个会话的消息暂时没加载出来"
- description="可能是网络波动导致历史读取失败。点下面重试,或直接发消息继续对话。"
- [retryable]="true"
- (retry)="retry()"
- />
- } @else {
- <app-m-empty
- icon="fa-solid fa-comments"
- title="开始新的对话"
- description="发一条消息,数字生命就会开始工作"
- />
- }
- }
- @default {
- <!-- 触顶自动加载(不再需要按钮);这里只显示加载指示 -->
- @if (chat.paginating()) {
- <p class="m-load-more" aria-live="polite">
- <i class="fa-solid fa-circle-notch fa-spin" aria-hidden="true"></i>
- 正在加载更早的消息…
- </p>
- }
- <!--
- 回合聚合(2026-11-05):一次提问产生的多条 agent 消息合成**一条气泡**,
- 后到内容往里追加。过程行折叠在气泡顶部,执行中自动展开、完成后收起。
- -->
- <!--
- 卡片渲染(2026-11-07 用户需求):一轮 = 一张卡,
- 与桌面端共用 app-assistant-turn。用户消息仍走 app-m-msg,保持移动观感。
- -->
- @for (row of aiRows(); track row.key) {
- @if (row.kind === 'turn') {
- <!--
- 2026-12-02 用户裁决:恢复桌面同款等待反馈(删掉 hideRunningHint)。
- 此前(674428a)隐藏了「已处理 Ns · 继续处理任务过程」,声称由
- 「顶栏紫色进度条」替代 —— 但那个进度条从未实现,移动端等待期
- 变成零反馈(用户实测:回复动画全没了)。
- -->
- <app-assistant-turn
- [turn]="row.turn"
- [grouped]="false"
- (preview)="openFile($event)"
- (openTask)="goTask($event)"
- />
- } @else {
- <app-m-msg
- [message]="row.message"
- (retry)="retryMessage($event)"
- (openTask)="goTask($event)"
- />
- }
- }
- }
- }
- <!-- 与桌面同口径:回合卡已经在显示等待文案时,这里不再重复一条(2026-11-09) -->
- <!-- 2026-12-02 用户裁决:不展示容器命名(slug 感太重),固定文案「对方」 -->
- @if (chat.peerTyping() && aiRows().length === 0) {
- <p class="m-typing-line">对方正在输入…</p>
- }
- </ui-m-pull-refresh>
- </div>
- <div class="m-composer-area">
- <!--
- 容器连接中断提示(2026-12-03,用户实测:网关重启/崩溃时「输出中」无限转圈)。
- 信号 = Matrix presence(网关死 → /sync 断 → offline,秒~分钟级),
- 不用容器心跳(1 小时周期且网关崩了照发,判不出来)。
- 恢复在线后此条自动消失;Hermes 会从 sync 断点补收消息,通常无需重发。
- -->
- @if (connectionInterrupted()) {
- <div class="conn-interrupt" role="alert">
- <i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i>
- <span>容器连接中断,回复可能延迟或未送达</span>
- <button type="button" class="conn-interrupt-btn" (click)="resendPendingTurn()">重新发送</button>
- </div>
- }
- <!-- 待发消息持有条已移除(2026-11-14 用户裁决「永远不拦,直接发」) -->
- <!-- 待发附件:图片出缩略图(与 PC 端同构),其余出文件名 chip -->
- @if (chat.pendingFiles().length > 0) {
- <div class="m-pending" role="list" aria-label="待发送附件">
- @for (f of chat.pendingFiles(); track f.id) {
- @if (f.previewUrl) {
- <div class="m-pending-card" role="listitem">
- <img [src]="f.previewUrl" [alt]="f.file.name" class="m-pending-img" />
- <button
- type="button"
- class="m-pending-x"
- [attr.aria-label]="'移除 ' + f.file.name"
- (click)="chat.unstageFile(f.id)"
- >
- <i class="fa-solid fa-xmark" aria-hidden="true"></i>
- </button>
- </div>
- } @else {
- <span class="m-pending-item" role="listitem">
- <i class="fa-solid fa-paperclip" aria-hidden="true"></i>
- <span class="m-pending-name">{{ f.file.name }}</span>
- <button
- type="button"
- [attr.aria-label]="'移除 ' + f.file.name"
- (click)="chat.unstageFile(f.id)"
- >
- <i class="fa-solid fa-xmark" aria-hidden="true"></i>
- </button>
- </span>
- }
- }
- </div>
- }
- <!--
- 2026-12-02 用户裁决:输入区不展示容器命名 ——
- 删掉 [target](m-dock 的命名胶囊自动隐藏),placeholder 回到默认「发消息…」。
- -->
- <app-m-dock
- [draft]="chat.draft()"
- [disabled]="preparingRoom() || chat.state() === 'loading' || !!chat.agent()?.trialExpired"
- [hint]="sendHint()"
- [sending]="chat.sending()"
- [uploading]="chat.uploading()"
- [pct]="chat.uploadPct()"
- [stage]="chat.uploadPhase()"
- [hasAttachments]="chat.pendingFiles().length > 0"
- (draftChange)="chat.setDraft($event)"
- (send)="send($event)"
- (attach)="chat.stageFiles($event)"
- >
- <!--
- 项目切换器放进工具行(2026-11-23 用户要求):
- 原来是输入框上方独占一整行,纯占高度。现在收到附件按钮右侧同一行。
- dockTools 属性是 m-dock 里 ng-content select 的投影锚点。
- -->
- <ng-container ngProjectAs="[dockTools]">
- <app-m-project-switcher
- [(open)]="projectPickerOpen"
- [currentWorkspaceId]="chat.currentSession()?.workspaceId ?? null"
- [currentSessionId]="chat.currentSession()?.id ?? null"
- (openSession)="openProjectSession($event)"
- (newConversation)="startNewChatInProject($event)"
- />
- </ng-container>
- </app-m-dock>
- </div>
- </div>
- <!-- 全屏预览层(2026-11-03):点会话内文件/成果都走这里,不再新开标签页 -->
- <app-image-lightbox
- [open]="!!lightbox()"
- [url]="lightbox()?.url ?? ''"
- [name]="lightbox()?.name ?? ''"
- [size]="lightbox()?.size ?? 0"
- (closed)="lightbox.set(null)"
- />
- <app-file-preview
- [open]="!!preview()"
- [url]="preview()?.url ?? ''"
- [name]="preview()?.name ?? ''"
- [mimeType]="preview()?.mimeType ?? ''"
- mode="modal"
- (closed)="preview.set(null)"
- />
- <app-m-new-chat
- [open]="projectChatOpen()"
- (openChange)="onProjectChatOpenChange($event)"
- [(workspaceId)]="pendingProjectId"
- (created)="createProjectChat($event)"
- />
- <!--
- 会话标题编辑(2026-11-23 用户要求)
- 标题点击进来改显示名,只改房间名,不动消息内容。
- -->
- <app-m-title-editor
- [open]="titleEditorOpen()"
- [initial]="title()"
- (save)="onTitleSave($event)"
- (cancel)="titleEditorOpen.set(false)"
- />
- <!-- 成果抽屉(Demo 07:任务 / 文件 / 成果 / 状态) -->
- @if (sheetOpen()) {
- <div class="m-sheet-root" role="dialog" aria-modal="true" aria-label="会话面板" [appLockScroll]="true">
- <div class="m-sheet-mask" (click)="sheetOpen.set(false)"></div>
- <section class="m-sheet">
- <div class="m-grabber" aria-hidden="true"></div>
- <header class="m-sheet-head">
- <h2>{{ title() }}</h2>
- <button type="button" class="m-sheet-x" aria-label="关闭" (click)="sheetOpen.set(false)">
- <i class="fa-solid fa-xmark" aria-hidden="true"></i>
- </button>
- </header>
- <div class="m-sheet-tabs" role="tablist">
- @for (t of sheetTabs; track t.value) {
- <button
- type="button"
- role="tab"
- class="m-chip"
- [class.on]="sheetTab() === t.value"
- [attr.aria-selected]="sheetTab() === t.value"
- (click)="sheetTab.set(t.value)"
- >
- {{ t.label }}
- </button>
- }
- </div>
- <div class="m-sheet-body">
- @switch (sheetTab()) {
- @case ('task') {
- @if (relatedTasks().length > 0) {
- <ul class="m-list">
- @for (t of relatedTasks(); track t.id) {
- <li>
- <button
- type="button"
- class="m-row"
- [class.hl]="railHighlight() === t.id"
- (click)="goTask(t.id)"
- >
- <span class="m-row-body">
- <span class="m-row-t1">{{ t.title }}</span>
- <span class="m-row-t2">{{ t.updatedAt || '—' }}</span>
- </span>
- <app-m-badge [tone]="taskTone(t)">{{ taskText(t) }}</app-m-badge>
- </button>
- </li>
- }
- </ul>
- } @else {
- <app-m-empty title="暂无任务" [compact]="true" />
- }
- }
- @case ('file') {
- @if (files().length > 0) {
- <ul class="m-list">
- @for (f of files(); track f.url + f.name) {
- <li>
- <!-- 点开走全屏预览(2026-11-03),不再新开标签页 -->
- <button type="button" class="m-row" (click)="openFile(f)">
- <i class="fa-solid fa-file" aria-hidden="true"></i>
- <span class="m-row-body">
- <span class="m-row-t1">{{ f.name }}</span>
- <span class="m-row-t2">{{ fmtSize(f.size) }}</span>
- </span>
- <i class="fa-solid fa-chevron-right m-chev" aria-hidden="true"></i>
- </button>
- </li>
- }
- </ul>
- } @else {
- <app-m-empty title="暂无文件" [compact]="true" />
- }
- }
- @case ('deliver') {
- <!--
- 未上云提示(2026-11-09),与桌面 session-rail 同口径。
- 附件没有 url 时原来静默不显示,用户以为文件丢了。
- -->
- @if (notOnCloudCount() > 0) {
- <p class="m-rail-warn" role="status">
- <i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i>
- 有 {{ notOnCloudCount() }} 个成果文件未上传云盘,暂时无法查看
- </p>
- }
- @if (deliverables().length > 0) {
- @for (d of deliverables(); track d.id) {
- <div class="m-deliver">
- <div class="m-deliver-head">
- <span class="m-row-t1">{{ d.title }}</span>
- <span class="m-row-t2">{{ d.version || '' }} · {{ d.deliveredAt }}</span>
- </div>
- @if (d.artifacts.length > 0) {
- <ul class="m-list">
- <!-- 遍历全部产物(原实现只取 artifacts[0],其余看不到) -->
- @for (a of d.artifacts; track a.url || a.name) {
- <li>
- <button type="button" class="m-row" (click)="openFile(a)">
- <i class="fa-solid fa-paperclip" aria-hidden="true"></i>
- <span class="m-row-body">
- <span class="m-row-t1">{{ a.name }}</span>
- <span class="m-row-t2">{{ a.type || '' }}</span>
- </span>
- <i class="fa-solid fa-chevron-right m-chev" aria-hidden="true"></i>
- </button>
- </li>
- }
- </ul>
- } @else {
- <p class="m-deliver-empty">暂无可用产物</p>
- }
- </div>
- }
- } @else {
- <app-m-empty title="暂无成果" [compact]="true" />
- }
- }
- @default {
- <dl class="m-kv">
- <dt>状态</dt>
- <!-- 统一口径(2026-11-08):原先直接渲染 statusText ?? status,英文 id 会露出 -->
- <dd>{{ agentState()?.text ?? '—' }}</dd>
- <dt>当前任务</dt>
- <dd>{{ agent()?.currentTask || '—' }}</dd>
- <dt>最近在线</dt>
- <dd>{{ heartbeatText() }}</dd>
- <dt>连接</dt>
- <dd>{{ chat.connection() === 'connected' ? '已连接' : '未连接' }}</dd>
- <dt>会话</dt>
- <dd>{{ title() }}</dd>
- </dl>
- }
- }
- </div>
- </section>
- </div>
- }
- `,
- styles: [
- `
- :host {
- display: block;
- }
- .m-page {
- display: flex;
- flex-direction: column;
- height: 100dvh;
- background: var(--surface);
- }
- .m-fab {
- display: grid;
- place-items: center;
- width: var(--touch-min);
- height: var(--touch-min);
- border: 0;
- border-radius: var(--r-tag);
- background: transparent;
- box-shadow: none;
- color: var(--ink);
- font-size: var(--fs-icon);
- cursor: pointer;
- }
- /* 试用到期提示条(2026-12-03):与连接中断条同风格,左侧文案 + 右侧去开通 */
- .trial-expired-bar {
- display: flex;
- align-items: center;
- gap: var(--sp-2);
- width: calc(100% - var(--mob-gutter) * 2);
- margin: var(--sp-2) var(--mob-gutter) 0;
- padding: var(--sp-2) var(--sp-3);
- border: 1px solid var(--warning);
- border-radius: var(--r-md);
- background: var(--warning-subtle);
- color: var(--warning);
- font-size: var(--fs-12);
- line-height: 1.4;
- }
- .trial-expired-bar > span {
- flex: 1;
- min-width: 0;
- }
- .trial-expired-btn {
- flex: none;
- min-height: 32px;
- padding: 0 var(--sp-3);
- border: 1px solid var(--warning);
- border-radius: 8px;
- background: transparent;
- color: var(--warning);
- font-size: var(--fs-12);
- cursor: pointer;
- }
- .m-conn-bar {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: var(--sp-2);
- width: calc(100% - var(--mob-gutter) * 2);
- margin: 0 var(--mob-gutter);
- padding: var(--sp-2) var(--sp-3);
- border: 1px solid var(--warning);
- border-radius: var(--r-md);
- background: var(--warning-subtle);
- color: var(--warning);
- font: inherit;
- font-size: var(--fs-12);
- cursor: pointer;
- }
- /* 回环提示条(与 m-conn-bar 同一套 warning 令牌,但主体是说明 + 独立动作按钮) */
- .m-loop-bar {
- display: flex;
- align-items: center;
- gap: var(--sp-2);
- width: calc(100% - var(--mob-gutter) * 2);
- margin: 0 var(--mob-gutter) var(--sp-2);
- padding: var(--sp-2) var(--sp-3);
- border: 1px solid var(--warning);
- border-radius: var(--r-md);
- background: var(--warning-subtle);
- color: var(--warning); font-size: var(--fs-12);
- }
- .m-loop-text {
- display: flex;
- align-items: center;
- gap: var(--sp-2);
- flex: 1;
- min-width: 0;
- } .m-loop-text span {
- /* 提示较长,允许换行但不挤掉按钮 */
- overflow-wrap: anywhere;
- }
- /* 未上云的成果提示(2026-11-09),与桌面 rail-warn 同口径 */
- .m-rail-warn {
- display: flex;
- align-items: flex-start;
- gap: var(--sp-1);
- margin: var(--sp-2) var(--mob-gutter) 0;
- padding: var(--sp-2) var(--sp-3);
- border-radius: var(--r-tag);
- background: var(--warning-subtle);
- color: var(--warning);
- font-size: var(--fs-13);
- line-height: 1.5;
- }
- .m-loop-act {
- flex: none;
- /* 触达区 ≥44px(WCAG 2.2 AA) */
- min-height: 44px;
- padding: 0 var(--sp-3);
- border: 1px solid var(--warning);
- border-radius: var(--r-sm);
- background: transparent;
- color: var(--warning);
- font: inherit;
- font-size: var(--fs-13);
- cursor: pointer;
- }
- .m-turn {
- display: flex;
- flex-direction: column;
- gap: var(--sp-3);
- }
- .m-turn-head {
- display: inline-flex;
- align-items: center;
- gap: var(--sp-2);
- align-self: flex-start;
- min-height: 28px;
- padding: 0 var(--sp-3);
- border: 1px solid var(--edge);
- border-radius: var(--r-tag);
- background: var(--surface-2);
- color: var(--muted);
- font: inherit;
- font-size: var(--fs-12);
- cursor: pointer;
- }
- .m-exec {
- color: var(--info);
- }
- .m-chat-body {
- flex: 1;
- min-height: 0;
- overflow-y: auto;
- -webkit-overflow-scrolling: touch;
- display: flex;
- flex-direction: column;
- gap: var(--sp-4);
- padding: var(--sp-3) var(--mob-gutter) var(--sp-6);
- }
- .m-load-more {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: var(--sp-2);
- margin: 0;
- padding: var(--sp-2);
- color: var(--muted);
- font-size: var(--fs-12);
- }
- .m-typing-line {
- margin: 0;
- color: var(--muted);
- font-size: var(--fs-12);
- }
- .m-loading {
- display: grid;
- place-items: center;
- gap: var(--sp-3);
- padding: var(--sp-8);
- }
- /* 建会话/加载中的说明文字(2026-11-13) */
- .m-loading-text {
- margin: 0;
- font-size: var(--fs-13);
- color: var(--muted);
- }
- .m-typing {
- display: inline-flex;
- gap: 4px;
- }
- .m-typing i {
- width: 6px;
- height: 6px;
- border-radius: var(--r-tag);
- background: var(--edge-strong);
- animation: m-bounce 1s infinite ease-in-out;
- }
- .m-typing i:nth-child(2) {
- animation-delay: 0.15s;
- }
- .m-typing i:nth-child(3) {
- animation-delay: 0.3s;
- }
- @keyframes m-bounce {
- 0%,
- 80%,
- 100% {
- transform: translateY(0);
- opacity: 0.4;
- }
- 40% {
- transform: translateY(-4px);
- opacity: 1;
- }
- }
- .m-composer-area {
- /* 待发消息提示条样式已移除(2026-11-14 持有条机制下线) */
- flex: none;
- padding-bottom: calc(var(--mob-safe-bottom) + var(--sp-3));
- /*
- * 2026-12-02 用户裁决:
- * ① 删掉 background: var(--surface) —— 输入区背景透明融入消息流
- * (桌面端同区域就是透明的),坞体卡片自带 --surface-2 不变;
- * ② 删掉 padding-inline: var(--mob-gutter) —— m-dock 自身已有
- * margin-inline: var(--mob-gutter),两层叠加让输入框比消息流窄一截。
- */
- }
- /* 容器连接中断提示条(2026-12-03):与 m-dock 同宽(对齐 gutter) */
- .conn-interrupt {
- display: flex;
- align-items: center;
- gap: var(--sp-2);
- margin: 0 var(--mob-gutter) var(--sp-2);
- padding: var(--sp-2) var(--sp-3);
- border-radius: 10px;
- background: var(--warning-subtle);
- color: var(--warning);
- font-size: var(--fs-12);
- line-height: 1.4;
- }
- .conn-interrupt > span {
- flex: 1;
- min-width: 0;
- }
- .conn-interrupt-btn {
- flex: none;
- min-height: 32px;
- padding: 0 var(--sp-3);
- border: 1px solid var(--warning);
- border-radius: 8px;
- background: transparent;
- color: var(--warning);
- font-size: var(--fs-12);
- cursor: pointer;
- }
- .m-pending {
- display: flex;
- gap: var(--sp-2);
- padding: 0 var(--mob-gutter) var(--sp-2);
- overflow-x: auto;
- scrollbar-width: none;
- }
- .m-pending::-webkit-scrollbar {
- display: none;
- }
- /* 图片待发卡:缩略图 + 右上角移除 */
- .m-pending-card {
- position: relative;
- flex: none;
- width: 72px;
- height: 72px;
- border-radius: var(--r-md);
- overflow: hidden;
- border: 1px solid var(--edge);
- background: var(--surface-2);
- }
- .m-pending-img {
- width: 100%;
- height: 100%;
- object-fit: cover;
- display: block;
- }
- .m-pending-x {
- position: absolute;
- top: 2px;
- right: 2px;
- display: grid;
- place-items: center;
- width: var(--touch-min);
- height: var(--touch-min);
- padding: 0;
- border: 0;
- border-radius: var(--r-tag);
- background: color-mix(in srgb, var(--ink) 70%, transparent);
- color: var(--surface);
- font-size: var(--fs-10);
- cursor: pointer;
- }
- .m-pending-item {
- display: inline-flex;
- align-items: center;
- gap: var(--sp-2);
- max-width: 100%;
- padding: var(--sp-1) var(--sp-2);
- border: 1px solid var(--edge);
- border-radius: var(--r-sm);
- background: var(--surface);
- color: var(--ink-2);
- font-size: var(--fs-12);
- }
- .m-pending-name {
- max-width: 160px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .m-pending-item button {
- min-width: var(--touch-min);
- min-height: var(--touch-min);
- border: 0;
- background: none;
- color: var(--muted);
- cursor: pointer;
- padding: 0;
- }
- .m-sheet-root {
- position: fixed;
- inset: 0;
- z-index: var(--z-modal);
- }
- .m-sheet-mask {
- position: absolute;
- inset: 0;
- background: var(--overlay);
- }
- .m-sheet {
- position: absolute;
- left: 0;
- right: 0;
- bottom: 0;
- display: flex;
- flex-direction: column;
- /* 默认全屏(2026-11-03 用户要求):原来是 max-height:82%,内容矮时只占一小块 */
- height: 100dvh;
- max-height: 100dvh;
- padding-top: var(--mob-safe-top);
- padding-bottom: var(--mob-safe-bottom);
- border-radius: var(--r-sheet) var(--r-sheet) 0 0;
- box-sizing: border-box;
- background: var(--surface);
- box-shadow: var(--shadow-overlay);
- animation: m-sheet-in var(--motion-panel) var(--ease-standard);
- }
- .m-grabber {
- width: 36px;
- height: 4px;
- margin: var(--sp-2) auto;
- border-radius: var(--r-tag);
- background: var(--edge-strong);
- }
- .m-sheet-head {
- display: flex;
- align-items: center;
- gap: var(--sp-3);
- padding: var(--sp-2) var(--mob-gutter) var(--sp-3);
- }
- .m-sheet-head h2 {
- flex: 1;
- margin: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- color: var(--ink);
- font-size: var(--fs-17);
- }
- .m-sheet-x {
- display: grid;
- place-items: center;
- width: var(--touch-min);
- height: var(--touch-min);
- border: 0;
- border-radius: var(--r-tag);
- background: none;
- color: var(--muted);
- font-size: var(--fs-icon);
- cursor: pointer;
- }
- .m-sheet-tabs {
- display: flex;
- gap: var(--sp-2);
- padding: 0 var(--mob-gutter) var(--sp-3);
- overflow-x: auto;
- }
- .m-chip {
- flex: none;
- height: 34px;
- padding: 0 var(--sp-3);
- border: 1px solid var(--edge);
- border-radius: var(--r-tag);
- background: var(--surface);
- color: var(--ink-2);
- font: inherit;
- font-size: var(--fs-13);
- cursor: pointer;
- }
- .m-chip.on {
- border-color: var(--primary);
- background: var(--primary);
- color: var(--primary-content);
- font-weight: 600;
- }
- .m-sheet-body {
- overflow-y: auto;
- padding: 0 var(--mob-gutter) var(--sp-6);
- }
- .m-list {
- margin: 0;
- padding: 0;
- list-style: none;
- border: 1px solid var(--edge);
- border-radius: var(--r-lg);
- overflow: hidden;
- }
- .m-list > li + li {
- border-top: 1px solid var(--edge);
- }
- .m-row {
- display: flex;
- align-items: center;
- gap: var(--sp-3);
- width: 100%;
- min-height: 56px;
- padding: var(--sp-3) var(--sp-4);
- box-sizing: border-box;
- border: 0;
- background: var(--surface);
- color: var(--ink);
- font: inherit;
- text-align: left;
- text-decoration: none;
- cursor: pointer;
- }
- /* 深链定位高亮(2026-11-11):任务引用点进来时短暂标出是哪条 */
- .m-row.hl {
- background: var(--surface-hover);
- box-shadow: inset 3px 0 0 var(--primary);
- }
- .m-row-body {
- flex: 1;
- min-width: 0;
- }
- .m-row-t1,
- .m-row-t2 {
- display: block;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .m-row-t1 {
- font-size: var(--fs-15);
- }
- .m-row-t2 {
- color: var(--muted);
- font-size: var(--fs-13);
- }
- .m-kv {
- display: grid;
- grid-template-columns: 96px 1fr;
- gap: var(--sp-2) var(--sp-3);
- margin: 0;
- padding: var(--sp-4);
- border: 1px solid var(--edge);
- border-radius: var(--r-lg);
- font-size: var(--fs-13);
- }
- .m-kv dt {
- color: var(--muted);
- }
- .m-kv dd {
- margin: 0;
- color: var(--ink);
- word-break: break-all;
- }
- /*
- * 统一的弹层进场(2026-11-23):从底部上浮 40px + 淡入,240ms 标准缓动。
- * 原来这里是「从屏幕外整个滑入 translateY(100%)」,与选择项目浮卡的
- * 「浮起 24px」不一致 —— 同样是从底部出来,一个扫过整屏、一个只轻抬一下。
- * 现在全端统一为「轻抬」:有方向感,又不制造长距离运动。
- */
- @keyframes m-sheet-in {
- from {
- transform: translateY(40px);
- opacity: 0;
- }
- to {
- transform: translateY(0);
- opacity: 1;
- }
- }
- @media (prefers-reduced-motion: reduce) {
- .m-sheet,
- .m-typing i {
- animation: none;
- }
- }
- `,
- ],
- })
- export class MbChatPage implements OnDestroy {
- private readonly route = inject(ActivatedRoute);
- private readonly router = inject(Router);
- private readonly tasksSvc = inject(TasksService);
- private readonly sessionsSvc = inject(ChatSessionService);
- private readonly view = inject(MobileChatViewService);
- /** 成果列表构造(从 agent 消息附件生成) */
- private readonly deliverablesSvc = inject(DeliverablesService);
- /** 容器成果 → 会话台账的绑定兜底(2026-11-13) */
- protected readonly fileBinding = inject(AgentFileBindingService);
- protected readonly chat = inject(ChatService);
- private readonly incomingShares = inject(ShareReceiveService);
- protected readonly loop = inject(LoopGuardService);
- /**
- * 任务脉冲(2026-11-14 接入)。
- *
- * 桌面端聊天顶栏早就用 `pulse.describe()` 显示「正在处理…」,
- * 手机端却只有「在线 / 正在回复」——用户在手机上根本看不出容器到底在不在干活。
- * 这里补齐,与桌面端同一判据、同一文案来源。
- */
- protected readonly pulse = inject(TaskPulseService);
- protected readonly sheetOpen = signal(false);
- protected readonly projectPickerOpen = signal(false);
- protected readonly projectChatOpen = signal(false);
- protected readonly pendingProjectId = signal<string | null>(null);
- /** 图片走灯箱 */
- protected readonly lightbox = signal<{ url: string; name: string; size: number } | null>(null);
- /**
- * 正在为新建会话开独立房间(2026-11-13)。
- *
- * 🔴 桌面端在「新建对话」弹窗里显示「正在准备会话…」,移动端没有对应位置 ——
- * 点选容器后面板立刻关闭,要等 0.6~0.7 秒建房完成才跳转,
- * 这段时间屏幕上什么都没发生,用户以为点了没反应(真机实测反馈)。
- * 这里在会话页给出明确反馈。
- */
- protected readonly preparingRoom = signal(false);
- /**
- * 发送按钮的提示(2026-11-13)。
- *
- * 忙碌时明确告知「发送会打断当前任务」——实测确认的行为
- * (容器 `busy_input_mode=interrupt`,0.7 秒内打断并响应)。
- */
- readonly sendHint = computed(() =>
- this.chat.sessionBusy() ? '发送将打断当前任务' : '',
- );
- /** 其余文件走全屏预览 */
- protected readonly preview = signal<{ url: string; name: string; mimeType: string } | null>(null);
- protected readonly sheetTab = signal<SheetTab>('task');
- /**
- * 抽屉里需要高亮定位的任务 id(2026-11-11)。
- *
- * 「任务」页路由下线后,消息里的任务引用改为「打开抽屉 + 定位」,
- * 与桌面 `openRailAt()` 同口径,2 秒后自动清空。
- */
- protected readonly railHighlight = signal<string | null>(null);
- private railHighlightTimer: ReturnType<typeof setTimeout> | null = null;
- /** 抽屉在本页不使用(返回即可),保留导入以便后续「会话切换」扩展 */
- protected readonly drawerOpen = signal(false);
- protected readonly sheetTabs: { value: SheetTab; label: string }[] = [
- { value: 'task', label: '任务' },
- { value: 'file', label: '文件' },
- { value: 'deliver', label: '成果' },
- { value: 'state', label: '状态' },
- ];
- protected readonly fmtSize = fmtSize;
- protected readonly agent = computed(() => this.chat.agent());
- /* agentName 已删除(2026-12-02 用户裁决:移动端会话页不展示容器命名) */
- /**
- * 容器离线 + 本端还有没等到回复的回合 → 显示「连接中断」提示条(2026-12-03)。
- *
- * 判定用 `chat.agentPresence()`(Matrix presence,秒~分钟级)而**不是**容器心跳
- * (1 小时周期且与网关进程无关,网关崩了照发)。
- * `'unknown'`(sync 未就绪)不告警,避免进页瞬间误报。
- */
- protected readonly connectionInterrupted = computed(() => {
- if (this.chat.agentPresence() !== 'offline') return false;
- return (
- this.chat.awaitingReplySince() > 0 ||
- this.aiRows().some((r) => r.kind === 'turn' && r.turn.live)
- );
- });
- /**
- * 「连接中断」提示条上的重新发送:取最后一个回合的用户原文重发(2026-12-03)。
- *
- * 注意:Hermes 恢复后会从 sync 断点补收消息,多数情况**不需要**重发;
- * 这个按钮是「等了很久还没恢复」时的逃生口,代价是恢复后可能收到两条回复。
- */
- protected resendPendingTurn(): void {
- const turns: AssistantTurn[] = [];
- for (const r of this.aiRows()) if (r.kind === 'turn') turns.push(r.turn);
- const text = [...turns].reverse().find((t) => t.userMessage?.text?.trim())?.userMessage?.text?.trim();
- if (!text) return;
- void this.chat.sendText(text);
- }
- /**
- * 消息 → 渲染行:**连续的终端活动消息合并成一个折叠组**。
- *
- * 与桌面端同一套规则(`desktop/pages/chat/chat.ts` 的 `messageRows`):
- * · 容器把 Hermes 每一步都作为独立消息发出(💻 terminal + 命令)
- * · 相邻且都属于终端活动 → 合成一组;遇到正常对话立即断开
- *
- * 🔴 组 key 用**组内第一条消息的 id**,不能用下标:
- * 流式追加时下标会变,导致同组被销毁重建(内容闪烁)。
- */
- /**
- * 消息 → 渲染行(2026-11-05 改为**回合聚合**)。
- *
- * ## 变化
- *
- * 原来:每条 agent 消息一个气泡 → 一条回答被容器拆成 2~3 条,读起来断续。
- * 现在:**一次提问的所有 agent 输出合成一个回合(一条气泡)**,内容往里追加。
- *
- * ## 边界
- *
- * `buildTurns` 负责切分(用户消息锚点 + typing 结束静默 3 秒),
- * 本方法只负责把回合映射成渲染行 —— 逻辑分离,便于单测。
- *
- * ## 兼容
- *
- * 用户消息仍逐条渲染;回合内的过程行(💻 terminal 等)折叠到回合顶部。
- */
- /**
- * 渲染行(2026-11-07 用户需求):AI 的一整轮合并成一张卡。
- *
- * 与桌面端共用 `app-assistant-turn` —— 用户裁决「复用同一个组件」,
- * 移动端差异(触达区 44px、字号 ≥16px、段间距)由组件内的
- * `bp.below-mobile` 分支处理,两处渲染逻辑保持单一来源。
- */
- protected readonly aiRows = computed<AiRow[]>(() => {
- const out: AiRow[] = [];
- /*
- * 🔴 依赖 `clockTick` 而不是 `now`(2026-11-10,与桌面端同口径)。
- *
- * 原来这里读 `this.now()`,于是时钟每秒推进都会让**整页 aiRows 重算**,
- * 每个 turn 对象都是新引用 → `app-assistant-turn` 的 input 变化 →
- * 流式推进的 `shownMap` 可能被重置,正文从头重放。
- * `clockTick` 是个计数器:每秒变一次,但只让**读它的地方**重算,
- * 回合数据本身只在消息变化时重建。
- */
- this.clockTick();
- const now = Date.now();
- /*
- * 🔴 跨回合全局文件去重(2026-11-18 用户裁决「全局去重」)。
- *
- * ## 现象
- *
- * 容器在第 1 回合发了 `table.html`,第 2 回合又发了一次(重发 / 补充),
- * 两个回合各出一张卡片 —— 用户看到两张一模一样的卡,以为是 bug。
- *
- * ## 为什么回合内的去重不够
- *
- * `collectFiles()` 只在**单个回合**内去重。跨回合时每回合各自算出自己的文件列表,
- * 同一份产物在两个回合里各出现一次。
- *
- * ## 做法
- *
- * 按「文件名 + 大小」做全局签名表,**后出现的回合**里把已出现过的文件剔掉。
- * 保留最早那次 —— 那是容器第一次交付的位置,更符合「文件在这里产生」的语义。
- *
- * 只影响**显示**;`turn().files` 原始数据不变,对账与其他逻辑不受影响。
- */
- const seenFileSigs = new Set<string>();
- const dedupeTurnFiles = <T extends { files?: { file: { name: string; size?: number } }[] }>(
- turn: T,
- ): T => {
- const files = turn.files;
- if (!files?.length) return turn;
- const kept = files.filter((f) => {
- const sig = `${f.file.name}|${f.file.size ?? 0}`;
- if (seenFileSigs.has(sig)) return false;
- seenFileSigs.add(sig);
- return true;
- });
- /* 全部被去重掉 → 不新建对象(保持引用稳定,避免组件 input 变化) */
- if (kept.length === files.length) return turn;
- return { ...turn, files: kept } as T;
- };
- for (const t of turnsFromDm(
- buildTurns({ messages: this.chat.messages(), typing: this.chat.peerTyping(), now }),
- now,
- this.chat.peerTyping(),
- /* 与桌面同口径(2026-11-08):25 秒静默窗口 + 容器明确空闲时立即收尾 */
- QUIET_MS,
- this.chat.agentIdle(),
- /* 容器结束信号(2026-11-11):`m.typing=false` 的本地接收时刻,与桌面同口径 */
- this.chat.turnEndedAfter(),
- )) {
- /* 连发的前置提问先展示(2026-11-11,与桌面同口径) */
- for (const prevAsk of t.priorAsks ?? []) {
- out.push({ kind: 'msg', key: prevAsk.id, message: prevAsk });
- }
- if (t.userMessage) {
- out.push({ kind: 'msg', key: t.userMessage.id, message: t.userMessage });
- }
- // 同一轮输入里的附件紧跟文字(2026-11-10,与桌面同口径)
- for (const f of t.userFiles ?? []) {
- out.push({ kind: 'msg', key: f.id, message: f });
- }
- // 已发出等待回复 / 有用户附件 也要出卡(2026-11-09 / 2026-11-10,与桌面同口径)
- if (t.merged || t.live || t.userMessage || (t.userFiles?.length ?? 0) > 0) {
- out.push({ kind: 'turn', key: `turn-${t.id}`, turn: dedupeTurnFiles(t) });
- }
- }
- return out;
- });
- /*
- * 超时未响应的全局提示(2026-11-10 用户裁决,与桌面同口径)。
- *
- * 🔴 不自动消失,必须用户手动关闭。
- * 🔴 不只要弹一次:**当前会话只要存在超时回合,就要一直显示**;
- * 条件消失(收到回复)后自动撤掉,避免残留。
- */
- private readonly alert = inject(AlertService);
- /**
- * 轻提示(2026-11-14)。
- *
- * 底座 `UiMToastService`:2 秒自动消失的普通提示 —— 「任务完成」正好属于
- * alert.service 注释里划给它的那一类(不该用常驻的告警条,那会一直杵在屏上)。
- * 容器已由 `app.ts` 全局挂载 `UiMToast`,直接注入即可。
- */
- /** Android 返回键接管(2026-11-15):弹层开着时返回键只关弹层 */
- private readonly backBtn = inject(BackButtonService);
- private static readonly TIMEOUT_TITLE = '容器长时间未响应';
- private watchTurnTimeout(turns: readonly AssistantTurn[]): void {
- /*
- * 🔴 只看最后一轮(2026-11-10,与桌面同口径):更早的回合不论有没有回复,
- * 都已经过去了,不该弹提示。
- */
- const last = turns[turns.length - 1];
- if (!last) {
- this.alert.syncState(MbChatPage.TIMEOUT_TITLE, false);
- return;
- }
- /* 已处理过的超时 → 直接抛弃,不再判定(用户裁决 2026-11-10) */
- if (this._handledTimeouts.has(last.id)) {
- this.alert.syncState(MbChatPage.TIMEOUT_TITLE, false);
- return;
- }
- const userMs = last.userMessage ? Date.parse(last.userMessage.ts) || 0 : 0;
- const hasOutput = last.blocks.some((b) => b.body.length > 0 || b.steps.length > 0);
- const timedOut = userMs > 0 && isTurnTimedOut(Date.now() - userMs, hasOutput, last.live);
- /* 卡住检测(2026-11-11,与桌面同口径):回了一部分就停住的情况 */
- const lastActivity = last.blocks.reduce((max, b) => Math.max(max, b.updatedAt), 0);
- const idleMs = lastActivity > 0 ? Date.now() - lastActivity : 0;
- const stalled = isTurnStalled(idleMs, hasOutput, last.live);
- if (timedOut || stalled) {
- this._handledTimeouts.add(last.id);
- this.alert.resetDismiss(MbChatPage.TIMEOUT_TITLE);
- this.alert.syncState(
- MbChatPage.TIMEOUT_TITLE,
- true,
- stalled
- ? `容器已停止响应超过 ${Math.round(STALL_MS / 1000)} 秒,任务可能已中断。可点「重新发送」把刚才的消息放回输入框。`
- : `最近一条消息已超过 ${Math.round(TURN_TIMEOUT_MS / 1000)} 秒没有回复。请确认容器是否在线,或点「重新发送」重试。`,
- { label: '重新发送' },
- );
- return;
- }
- this.alert.syncState(MbChatPage.TIMEOUT_TITLE, false);
- }
- /** 把最后一条用户消息放回输入框(2026-11-11,与桌面同口径,不自动发送) */
- private resendLast(): void {
- const mine = [...this.chat.messages()].reverse().find((m) => m.sender === 'me' && m.text?.trim());
- if (!mine?.text) return;
- this.chat.setDraft(mine.text);
- this.alert.show('已放回输入框', '确认内容无误后再点发送即可。', 'warning');
- }
- /**
- * 已处理过(提示过)的超时回合 id。
- *
- * 🔴 用户裁决:超时一次性处理,之后直接抛弃。
- * 只存内存、不落盘 —— 落盘会跨账号串数据(用户明确否决)。
- */
- private readonly _handledTimeouts = new Set<string>();
- /**
- * 把回合内**连续的 agent 正文**合成一个块(2026-11-06 用户要求)。
- *
- * 容器常把一条回答拆成多条消息;此前每段各占一个块,读起来是碎片。
- * 工具块、附件、失败消息各自断开,规则见 `core/message-merge.ts`。
- */
- /**
- * 时钟计数器:每秒 +1,**只用于驱动依赖它的 computed 重算**(2026-11-10)。
- *
- * 与桌面端 `clockTick` 同口径。不要改成「读一个 Date.now() 快照信号」——
- * 那样整页回合数据每秒重建,流式动画会被打断。
- */
- private readonly clockTick = signal(0);
- private nowTimer: ReturnType<typeof setInterval> | null = null;
- /** 回合折叠状态(用户手动切换覆盖默认) */
- protected readonly title = computed(
- /*
- * 2026-12-02 用户裁决:标题兜底不再回落到容器名(机器 slug 不展示),
- * 会话没有标题时直接显示「会话」。
- */
- () => this.chat.currentSession()?.title ?? '会话',
- );
- /**
- * 标题编辑弹层开关(2026-11-23 用户要求「标题不能点击编辑」)
- *
- * 只在会话页开放 —— 标题来自 Matrix 房间名,改名走 m.room.name 状态事件,
- * 需要房间内的 power level。改不动时给个明确提示,不静默失败。
- */
- protected readonly titleEditorOpen = signal(false);
- protected openTitleEditor(): void {
- /*
- * 2026-11-23 修:原来这里有一道 `if (!roomId) return`。
- * 会话目录还没刷到时 currentSession() 给的是占位对象,可能没有 roomId,
- * 于是点标题完全没反应 —— 用户看到的就是「点了没动静」。
- *
- * 标题编辑器打开不需要 roomId,只有保存时才需要。
- * 所以这里无条件打开,roomId 在保存那一刻再取。
- */
- this.titleEditorOpen.set(true);
- }
- /**
- * 保存标题。
- *
- * 写 Matrix 房间名(`m.room.name`)—— 这是标题的权威来源,
- * 本端和其他端(含其他成员的客户端)都会同步到。
- * 不改本地少量副本,避免两处状态打架。
- */
- protected async onTitleSave(next: string): Promise<void> {
- /*
- * roomId 兜底(2026-11-23):占位会话可能没有 roomId,
- * 但 sessionId 本身就是 Matrix 线程根、也就是房间 id 的来源。
- */
- const roomId = this.chat.currentSession()?.roomId ?? this.chat.sessionId();
- this.titleEditorOpen.set(false);
- if (!roomId) {
- console.warn('[chat] 没有 roomId,无法改名');
- return;
- }
- try {
- await this.chat.renameSession(roomId, next);
- } catch (e) {
- /*
- * 改名失败最常见的原因是权限不足(普通成员的 power level
- * 改不了 m.room.name)。原来只打 console,用户完全不知道发生了什么。
- */
- console.warn('[chat] 标题保存失败', e);
- }
- }
- /**
- * 在**当前容器**再开一条对话(2026-11-14)。
- *
- * 直接复用 `/chat/:agentId/new` —— 与 m-drawer 的「新建对话」最终落到同一条
- * 建房链路(`startBlankWithRoom`),不新造逻辑。
- */
- protected newChatInCurrent(agentId: string): void {
- this.drawerOpen.set(false);
- const workspaceId = this.chat.currentSession()?.workspaceId;
- const scope = workspaceId ? `?ws=${encodeURIComponent(workspaceId)}` : '';
- void this.router.navigateByUrl(`/mobile/chat/${encodeURIComponent(agentId)}/new${scope}`);
- }
- /** 从当前项目启动选数字生命流程;新会话继续沿用既有建房与归属逻辑。 */
- protected startNewChatInProject(workspaceId: string | null): void {
- this.drawerOpen.set(false);
- this.projectPickerOpen.set(false);
- this.pendingProjectId.set(workspaceId);
- this.projectChatOpen.set(true);
- }
- protected onProjectChatOpenChange(open: boolean): void {
- this.projectChatOpen.set(open);
- /*
- * 关闭时**不清空** pendingProjectId(2026-11-21):
- * 归属现在由弹层自己的下拉维护,用户选的默认值要保留到「创建」时读取。
- * 每次打开前,`startNewChatInProject` 会重新写入默认归属。
- */
- }
- protected createProjectChat(agentId: string): void {
- const workspaceId = this.pendingProjectId();
- this.projectChatOpen.set(false);
- this.pendingProjectId.set(null);
- const scope = workspaceId ? `?ws=${encodeURIComponent(workspaceId)}` : '';
- void this.router.navigateByUrl(`/mobile/chat/${encodeURIComponent(agentId)}/new${scope}`);
- }
- protected openProjectSession(row: { session: { id: string; agentId: string; kind?: string } }): void {
- if (row.session.kind === 'group') {
- void this.router.navigateByUrl(`/mobile/group/${encodeURIComponent(row.session.id)}`);
- return;
- }
- void this.router.navigateByUrl(
- `/mobile/chat/${encodeURIComponent(row.session.agentId)}/${encodeURIComponent(row.session.id)}`,
- );
- }
- /**
- * 容器名 + 状态(2026-11-11 收敛)。
- *
- * 与 PC 会话页头同一判据 `sessionPresence`:
- * 在线/离线走 `livenessOf`,本会话是否在回复单独叠加。
- * 离线时相位一律不显示(不能说明明断了还在回复)。
- */
- protected readonly presence = computed(() =>
- this.taskPresence(this.chat.agent()),
- );
- /**
- * 「在线 + 在干什么」的合并判定(2026-11-14)。
- *
- * 与桌面端 `desktop/pages/chat/chat.ts::taskLine()` 同一套口径:
- * ① 本回合刚收到 ✅ 且尚未刷新 → 直接「在线」,别让顶栏还转着
- * ② 容器在跑 → 用 `pulse.describe()` 的一句话任务文案
- * ③ 其余交回 `sessionPresence`(离线/回复中/在线)
- *
- * 只在**在线且正在干活**时接管文案;离线时一律走 liveness,
- * 不能因为本地还记着"刚才在跑"就瞒着用户说它在线。
- */
- private taskPresence(
- agent: Agent | undefined,
- ): { text: string; tone: SemanticTone; busy: boolean } {
- const base = sessionPresence(agent, this.chat.peerTyping() ? 'replying' : undefined);
- if (!base.busy && base.text === '在线' && this.chat.turnSettledLocally()) {
- return { text: '在线', tone: 'success', busy: false };
- }
- const line = this.pulse.describe(
- agent,
- Date.now(),
- this.chat.sessionId(),
- this.chat.currentRoomId(),
- this.chat.myMxId(),
- );
- if (!line.active) return base;
- const task = this.chat.sessionTaskLine();
- return {
- text: task || line.text || '正在处理…',
- tone: line.tone === 'neutral' ? 'info' : line.tone,
- busy: true,
- };
- }
- protected readonly subtitle = computed(() => {
- const a = this.chat.agent();
- if (!a) return '';
- /*
- * 🔴 本机断网时**优先报网络**(2026-11-16 真机实测补)。
- *
- * `presence()` 反映的是**容器**状态(在线/离线),跟本机网络无关。
- * 断网时容器数据还是断网前那份,于是顶栏继续显示「lj-test · 在线」——
- * 用户看着「在线」却发不出去消息,完全不知道为什么。
- *
- * 实测(小米 M2102K1AC / Android 14,飞行模式):
- * 会话页顶栏一直是「在线」,没有任何断网提示。
- */
- /*
- * 2026-12-02 用户裁决:副标题不再带容器命名(`xxx · 在线` 的 xxx 是
- * 机器 slug,用户看不懂),只留在线状态本身。
- */
- if (this.chat.connection() === 'disconnected') {
- return '网络已断开';
- }
- return this.presence().text;
- });
- /** 状态抽屉用同一个口径 */
- protected readonly agentState = computed(() => {
- const a = this.chat.agent();
- return a ? { text: this.presence().text, tone: this.presence().tone } : null;
- });
- /**
- * 心跳时间 → 人话(2026-11-08)。
- * 原先直接渲染 ISO 原文(`2026-11-08T03:12:44.000Z`),用户在手机上没法读。
- */
- protected readonly heartbeatText = computed(() => {
- const a = this.chat.agent();
- const sec = a?.heartbeatAgeSec;
- if (typeof sec === 'number' && Number.isFinite(sec)) {
- if (sec < 60) return `${Math.max(0, Math.round(sec))} 秒前`;
- if (sec < 3600) return `${Math.round(sec / 60)} 分钟前`;
- if (sec < 86400) return `${Math.round(sec / 3600)} 小时前`;
- return `${Math.round(sec / 86400)} 天前`;
- }
- const t = a?.heartbeatAt ? Date.parse(a.heartbeatAt) : NaN;
- if (!Number.isFinite(t)) return '—';
- return new Date(t).toLocaleString('zh-CN', { hour12: false });
- });
- /** 该会话下、该数字生命的任务(Demo 抽屉「任务」页签) */
- protected readonly relatedTasks = computed<Task[]>(() => {
- const id = this.chat.agentId();
- return id ? this.tasksSvc.all().filter((t) => t.agentId === id) : [];
- });
- /** 会话内出现过的全部附件(Demo 抽屉「文件」页签) */
- /**
- * 「文件」页签 = 本会话里**用户自己上传的**附件(2026-11-09 与桌面同口径)。
- *
- * 🔴 容器产出的不算「文件」,那是「成果」—— 见 `deliverables`。
- * 原来不看 sender,同一份成果在「文件」和「成果」各出现一次。
- */
- protected readonly files = computed(() => {
- const out: NonNullable<Message['file']>[] = [];
- const seen = new Set<string>();
- /*
- * ① 消息流里我发的附件 —— **先走这条**(2026-11-11,与桌面同口径):
- * 带真实 size 与 cloudUrl,信息最全。
- */
- for (const m of this.chat.messages()) {
- const f = m.file;
- if (m.sender !== 'me' || !f) continue;
- const id = fileIdentity(f.name, f.size);
- if (seen.has(id)) continue;
- seen.add(id);
- out.push(f);
- }
- /*
- * ② 台账里 `uploadedBy:'user'` 的记录:刷新后仍在,补上消息流翻页取不到的历史。
- *
- * 🔴 去重不能比 URL:台账存 S3 地址、消息流 `f.url` 是 `mxc://`,永远不等
- * → 同一个文件会出现两条(用户实测)。改按「名字+大小」。
- */
- for (const d of this._dbUserFiles()) {
- const a = d.artifacts[0];
- if (!a?.url) continue;
- const bytes = d.sizeBytes ?? 0;
- const id = fileIdentity(a.name, bytes);
- if (seen.has(id)) continue;
- seen.add(id);
- out.push({ kind: 'file', name: a.name, url: a.url, size: bytes > 0 ? bytes : -1, mimeType: a.type ?? '' });
- }
- return out;
- });
- /**
- * 成果抽屉「成果」页签 = **本会话里容器产出的文件**(2026-11-09 与桌面同口径)。
- *
- * 语义分界:
- * · 文件(`files`)= 我上传的
- * · 成果(这里) = 容器产出的
- *
- * 两个来源合并去重:会话记录 `deliverableUrls` + 消息流里 agent 发的文件。
- */
- protected readonly deliverables = computed(() => {
- const sess = this.chat.currentSession();
- /* 台账已按来源分流:成果只吃「容器产出」那半边(2026-11-11) */
- const fromDb = this.dbFiles();
- const agentFiles = agentMessageFiles(this.chat.messages());
- const fromMessages = this.deliverablesSvc.fromAgentFiles(agentFiles);
- const fromRecord = this.view.bySessionUrlsOf(sess?.deliverableUrls);
- return this.deliverablesSvc.merge(fromDb, fromMessages, fromRecord);
- });
- /**
- * 按会话从数据库加载的文件(2026-11-10:与桌面端同口径)。
- * 2026-11-11 起按来源分流,见 `_dbUserFiles` / `_dbFiles` 注释。
- */
- private readonly _dbUserFiles = signal<Deliverable[]>([]);
- private readonly _dbFiles = signal<Deliverable[]>([]);
- readonly dbFiles = this._dbFiles.asReadonly();
- /** 拉当前会话的文件台账;会话切换时重跑 */
- /**
- * 把 agent 消息里的容器产出链接补登进台账(2026-11-13)。
- *
- * 与桌面端 `DkChatPage.bindAgentFiles` 同口径:归属键用 roomId,
- * 缺 roomId 就跳过(宁可少补也不归错)。
- */
- private bindAgentFiles(sessionId: string): void {
- const roomId = this.chat.currentSession()?.roomId;
- if (!roomId) return;
- const urls = agentMessageFiles(this.chat.messages()).map((file) => file.url);
- if (urls.length === 0) return;
- void this.fileBinding.bindPending(roomId, sessionId, urls);
- }
- private loadSessionFiles(): void {
- const sid = this.chat.currentSession()?.id;
- if (!sid) {
- this._dbUserFiles.set([]);
- this._dbFiles.set([]);
- return;
- }
- void this.deliverablesSvc
- .loadSplitForSession(sid)
- .then(({ userFiles, agentFiles }) => {
- if (this.chat.currentSession()?.id !== sid) return;
- /* 内容没变就不写新数组(2026-11-13 请求风暴第二道防线,与桌面端同口径) */
- if (!sameDeliverableIds(this._dbUserFiles(), userFiles)) this._dbUserFiles.set(userFiles);
- if (!sameDeliverableIds(this._dbFiles(), agentFiles)) this._dbFiles.set(agentFiles);
- })
- .catch(() => {
- if (this.chat.currentSession()?.id === sid) {
- if (this._dbUserFiles().length > 0) this._dbUserFiles.set([]);
- if (this._dbFiles().length > 0) this._dbFiles.set([]);
- }
- });
- }
- /**
- * 🔴 同会话内的台账重拉去抖(2026-11-24 请求风暴第三道防线,
- * 与桌面端 `DkChatPage.scheduleSessionFilesReload` 同口径)。
- *
- * 下面的 effect 依赖 `messages().length`,Matrix 首次同步回放时它连续变化,
- * 旧实现每次都发一次无缓存的 `fetchFilesBySession` —— 实测 45 秒 710 个请求。
- * 口径:**切会话立即拉**(用户等着看成果区),**同会话消息变化去抖 2s 尾随拉一次**。
- */
- private filesReloadTimer: ReturnType<typeof setTimeout> | null = null;
- private lastFilesSid = '';
- private static readonly FILES_RELOAD_DEBOUNCE_MS = 2000;
- private scheduleSessionFilesReload(sid: string | undefined): void {
- if (this.filesReloadTimer) {
- clearTimeout(this.filesReloadTimer);
- this.filesReloadTimer = null;
- }
- if ((sid ?? '') !== this.lastFilesSid) {
- this.lastFilesSid = sid ?? '';
- this.loadSessionFiles();
- return;
- }
- this.filesReloadTimer = setTimeout(() => {
- this.filesReloadTimer = null;
- this.loadSessionFiles();
- }, MbChatPage.FILES_RELOAD_DEBOUNCE_MS);
- }
- /** 有多少成果附件还没上云(与桌面 `session-rail` 同口径) */
- protected readonly notOnCloudCount = computed(() =>
- this.deliverables().reduce((n, d) => n + d.artifacts.filter((a) => !a.url).length, 0),
- );
- private readonly scroller = viewChild<ElementRef<HTMLDivElement>>('scroller');
- /** 用户是否停在底部附近(不在底部时不自动滚动,避免打断向上翻历史) */
- private stickBottom = true;
- /**
- * 用户是否**主动**上翻离开了底部(2026-11-10,与桌面端 `userScrolledAway` 同口径)。
- *
- * 🔴 为什么 `stickBottom` 不够:
- * `stickBottom` 只记「此刻离底部多远」,而程序滚动本身也会触发 scroll 事件 ——
- * 用户上翻 → 新消息到达把列表拉回底部 → scroll 事件又把 `stickBottom` 置回 true →
- * 下一次新消息继续拉回。形成「上翻 → 被拽回 → 再也翻不上去」的死循环
- * (两轮回复交替到达时最明显,用户实测)。
- * 这里单独记「用户是不是主动走的」,且只在**用户自己滚动**时改变。
- */
- private userScrolledAway = false;
- /** 正在加载更早消息(防重入 + 分页期间不贴底) */
- private loadingEarlier = false;
- /** 上次贴底的时刻(节流用) */
- private lastStickAt = 0;
- protected retryMessage(id: string): void {
- void this.chat.retry(id);
- }
- constructor() {
- effect(() => {
- const transfer = this.incomingShares.transfer();
- const state = this.chat.state();
- const ready = state === 'ready' || state === 'empty';
- const agentId = this.chat.agentId();
- const sessionId = this.chat.sessionId();
- if (transfer && ready && agentId === transfer.agentId && sessionId === transfer.sessionId) {
- untracked(() => void this.incomingShares.stageInto(this.chat));
- } else if (transfer && state === 'error' && agentId === transfer.agentId) {
- untracked(() => this.incomingShares.cancelTransfer(this.chat.error() || '会话打开失败,请重试'));
- }
- });
- /* 提示条「重新发送」(2026-11-11,与桌面同口径) */
- this.alert.onAction((a) => {
- if (a.title === MbChatPage.TIMEOUT_TITLE) this.resendLast();
- });
- /*
- * Android 返回键接管(2026-11-15 真机问题修复)
- *
- * 🔴 不接管时的实测症状(两个,同一根因):
- * ① 打开文件预览后按返回 → 预览关掉的**同时会话也退出到列表**(退两层)
- * ② 偶发整屏白屏、15 秒不恢复,只能杀进程
- * 原因:弹层是组件内部状态,浏览器历史里没有对应记录,
- * 系统把返回键当「浏览器后退」,退掉的是上一个**路由**。
- *
- * 这里登记一个关闭器:只要有任一弹层开着,返回键只关弹层,不碰路由。
- * 后进先出 —— 用户看到的最上层先关。
- */
- effect((onCleanup) => {
- const anyOpen =
- this.drawerOpen() ||
- this.projectPickerOpen() ||
- this.projectChatOpen() ||
- this.sheetOpen() ||
- !!this.lightbox() ||
- !!this.preview();
- if (!anyOpen) return;
- this.backBtn.register('mobile-chat-overlays', () => {
- if (this.drawerOpen()) {
- this.drawerOpen.set(false);
- return true;
- }
- if (this.projectChatOpen()) {
- this.onProjectChatOpenChange(false);
- return true;
- }
- if (this.projectPickerOpen()) {
- this.projectPickerOpen.set(false);
- return true;
- }
- if (this.sheetOpen()) {
- this.sheetOpen.set(false);
- return true;
- }
- if (this.lightbox()) {
- this.lightbox.set(null);
- return true;
- }
- if (this.preview()) {
- this.preview.set(null);
- return true;
- }
- return false;
- });
- onCleanup(() => this.backBtn.unregister('mobile-chat-overlays'));
- });
- // 完成提醒由根部 TaskCompletionNotificationService 统一监听。
- /*
- * 右侧栏:会话切换或消息数变化时重拉文件台账(2026-11-10,与桌面端同口径)。
- * 容器产出的文件要等登记完才进台账,回合结束消息数变化正好触发刷新。
- */
- effect(() => {
- const sid = this.chat.currentSession()?.id;
- const count = this.chat.messages().length;
- /*
- * 🔴 `untracked` 必须加(2026-11-13 请求风暴修复,与桌面端同因)。
- *
- * `loadSessionFiles()` 内部会写 `_dbUserFiles` / `_dbAgentFiles`(新数组),
- * 而这些信号又被本 effect 的依赖链读到 —— 不隔离就会自我唤醒,
- * 实测 16.9 秒 418 个 `POST /api/functions`。
- *
- * 🔴 台账重拉还要去抖(2026-11-24,与桌面端同口径):
- * untracked 防自我唤醒,防不了回放期间 count 连续变化。
- */
- untracked(() => {
- this.scheduleSessionFilesReload(sid);
- /* 成果绑定兜底(2026-11-13,与桌面端同口径) */
- if (sid && count > 0) this.bindAgentFiles(sid);
- });
- });
- // 路由参数 → 打开会话;参数变化时重开
- this.route.paramMap.subscribe((pm) => {
- const agentId = pm.get('id');
- if (!agentId) return;
- const sid = pm.get('sessionId') ?? undefined;
- void this.openSession(agentId, sid);
- void this.tasksSvc.ensureAllLoaded();
- });
- // 新消息到达:贴底时滚到底(用户主动上翻期间不打扰,2026-11-10)
- effect(() => {
- this.chat.messages();
- if (this.loadingEarlier) return;
- if (this.stickBottom && !this.userScrolledAway) this.stickToBottom();
- });
- // 有活着的回合时才跑每秒时钟(见 `syncClock` 注释)
- effect(() => {
- this.aiRows();
- untracked(() => this.syncClock());
- });
- /*
- * 超时未响应 → 全局提示(2026-11-10,A2 重构,与桌面同口径)。
- *
- * 🔴 不再依赖 `now`。
- * 每秒时钟在「没有任何 live 回合」时停表,而超时恰恰发生在 live
- * 已变 false 之后 → 判定永远跑不到 → 提示不弹。
- * 现在只在这里同步看门狗开关,周期判定交给独立 interval。
- */
- effect(() => {
- this.aiRows();
- untracked(() => this.syncTimeoutWatch());
- });
- }
- ngOnDestroy(): void {
- // 离开会话不 close:Matrix 连接与未读计数需要保持(与桌面一致)
- if (this.nowTimer !== null) {
- clearInterval(this.nowTimer);
- this.nowTimer = null;
- }
- this.stopTimeoutWatch();
- // 去抖中的台账重拉也要清掉(2026-11-24 去抖引入,与桌面端同口径)
- if (this.filesReloadTimer) {
- clearTimeout(this.filesReloadTimer);
- this.filesReloadTimer = null;
- }
- }
- /*
- * 超时看门狗(2026-11-10,A2)。
- * 与 `syncClock` 分开:后者随 live 停表,前者只看「有无未回复的回合」。
- */
- private timeoutHandle: ReturnType<typeof setInterval> | null = null;
- private syncTimeoutWatch(): void {
- const waiting = this.hasPendingTurn();
- if (waiting && this.timeoutHandle === null) {
- this.timeoutHandle = setInterval(() => {
- this.evaluateTimeout();
- if (!this.hasPendingTurn()) this.stopTimeoutWatch();
- }, 5000);
- this.evaluateTimeout();
- } else if (!waiting && this.timeoutHandle !== null) {
- this.stopTimeoutWatch();
- }
- }
- private stopTimeoutWatch(): void {
- if (this.timeoutHandle !== null) {
- clearInterval(this.timeoutHandle);
- this.timeoutHandle = null;
- }
- }
- /** 是否存在「已发出、容器还没有任何输出」的回合(与 live 无关) */
- private hasPendingTurn(): boolean {
- /*
- * 🔴 2026-11-10 用户裁决:超时即终态,之后直接抛弃,不再监听。
- *
- * 只在「距发出还没超过超时窗口 + 10 秒」时才盯着。
- * 刷新页面时老消息早已超出窗口 → 看门狗不会启动 → 不会再弹。
- */
- const now = Date.now();
- return this.aiRows().some((r) => {
- if (r.kind !== 'turn') return false;
- const t = r.turn;
- if (!t.userMessage) return false;
- if (this._handledTimeouts.has(t.id)) return false;
- const userMs = Date.parse(t.userMessage.ts) || 0;
- if (!userMs) return false;
- if (now - userMs >= TURN_TIMEOUT_MS + 10_000) return false;
- return !t.blocks.some((b) => b.body.length > 0 || b.steps.length > 0);
- });
- }
- private evaluateTimeout(): void {
- const turns = this.aiRows().filter((r) => r.kind === 'turn').map((r) => r.turn);
- this.watchTurnTimeout(turns);
- }
- /*
- * 🔴 时钟驱动(2026-11-09,C2)。
- *
- * `now` signal 原先只有声明、没有任何地方 set —— `aiRows` 只在
- * `messages()` / `peerTyping()` 变化时重算。容器若一直报 typing、
- * 又不再发新消息,回合的「25 秒静默」永远等不到,卡片会一直挂在
- * 「正在输出…」(用户实测 163 秒)。
- *
- * 每秒推进一次 `now`,让静默判定真正随时间走。只在有活着的回合时起表,
- * 空闲页面不白跑定时器;离页即清。
- */
- private syncClock(): void {
- const needsTick = this.aiRows().some((r) => r.kind === 'turn' && r.turn.live);
- if (needsTick && this.nowTimer === null) {
- this.nowTimer = setInterval(() => {
- this.clockTick.update((n) => n + 1);
- if (!this.aiRows().some((r) => r.kind === 'turn' && r.turn.live)) {
- if (this.nowTimer !== null) clearInterval(this.nowTimer);
- this.nowTimer = null;
- }
- }, 1000);
- } else if (!needsTick && this.nowTimer !== null) {
- clearInterval(this.nowTimer);
- this.nowTimer = null;
- }
- }
- /**
- * 打开会话;`sessionId === 'new'` 为「新建对话」入口(与桌面 `/chat/:id/new` 同口径)。
- *
- * 🔴 建出会话后立刻 replaceUrl 成真实会话地址,避免刷新回到 `new`;
- * 这里**不调用 pruneEmpty**(桌面为此踩过坑:刚建的空会话被当成空壳删掉)。
- */
- private async openSession(agentId: string, sessionId?: string): Promise<void> {
- if (sessionId === 'new') {
- const ws = this.route.snapshot.queryParamMap.get('ws');
- /* 一房间一会话:建房完成后再进入(2026-11-12,与桌面端同口径) */
- this.preparingRoom.set(true);
- let created: Awaited<ReturnType<typeof this.chat.startBlankWithRoom>> = null;
- try {
- created = await this.chat.startBlankWithRoom(agentId, ws || null);
- } finally {
- this.preparingRoom.set(false);
- }
- if (created) {
- /*
- * 首页输入坞带过来的草稿(2026-11-09):用户先在首页打字、再选人,
- * 字不能丢。取回后立刻清掉,避免下次新建时又冒出来。
- */
- const carryKey = PENDING_DRAFT_KEY(agentId);
- const carried = sessionStorage.getItem(carryKey);
- if (carried) {
- sessionStorage.removeItem(carryKey);
- this.chat.setDraft(carried);
- }
- void this.router.navigateByUrl(
- `/mobile/chat/${agentId}/${encodeURIComponent(created.id)}`,
- { replaceUrl: true },
- );
- return;
- }
- } else {
- await this.chat.open(agentId, sessionId);
- this.sessionsSvc.pruneEmpty(this.chat.sessionId() ?? undefined);
- }
- this.stickBottom = true;
- this.userScrolledAway = false;
- this.lastStickAt = 0;
- queueMicrotask(() => this.scrollToBottom());
- void this.fillViewportIfNeeded();
- }
- protected send(text: string): void {
- /*
- * 自己发消息 = 明确想看结果 → 解除「用户上翻」保护并直接贴底。
- * 否则用户之前上翻过、发给新消息后还停在半空,看不到自己的消息和目标容器状态。
- */
- this.userScrolledAway = false;
- this.stickBottom = true;
- this.lastStickAt = 0;
- void this.chat.sendText(text);
- this.stickToBottom();
- }
- protected retry(): void {
- const agentId = this.route.snapshot.paramMap.get('id');
- const sid = this.route.snapshot.paramMap.get('sessionId') ?? undefined;
- if (agentId) void this.chat.open(agentId, sid, true);
- }
- protected reconnect(): void {
- this.retry();
- }
- /** 下拉刷新回调:强制重开当前会话(retry 已是 force 语义),等一拍让状态落地 */
- protected readonly onPullRefresh = (): Promise<void> => {
- this.reconnect();
- return new Promise((r) => setTimeout(r, 600));
- };
- protected loadMore(): void {
- void this.loadEarlier();
- }
- /**
- * 滚动处理:
- * ① 更新「是否贴底」(新消息到达时决定要不要自动滚到底)
- * ② **触顶自动加载更早消息**(与 PC 端 `desktop/pages/chat/chat.ts` 同口径)
- */
- protected onScroll(e: Event): void {
- const el = e.target as HTMLElement;
- const gap = el.scrollHeight - el.scrollTop - el.clientHeight;
- this.stickBottom = gap < 80;
- /*
- * 用户上翻的判定阈值比贴底恢复的阈值大(与桌面端 160px 同口径):
- * 只有明显离开底部才算「主动走开」,避免图片异步加载把高度撑大后误判。
- * 滚回接近底部时自动恢复贴底。
- */
- this.userScrolledAway = gap > 160;
- if (el.scrollTop > TOP_LOAD_PX) return;
- if (this.loadingEarlier || this.chat.paginating() || !this.chat.hasMoreHistory()) return;
- void this.loadEarlier();
- }
- /**
- * 加载更早的消息,并**保持视口位置不变**。
- *
- * 🔴 不做补偿的话,分页插入后 `scrollTop` 仍是原值,
- * 用户眼前的内容会整体往下窜(PC 端早期踩过,见 desktop chat.ts:2921-2940)。
- *
- * 做法与 PC 一致:记下加载前的 scrollHeight / scrollTop,等两帧让新内容完成布局,
- * 再把 scrollTop 加上新增的高度差。
- */
- private async loadEarlier(): Promise<void> {
- if (this.loadingEarlier) return;
- const el = this.scroller()?.nativeElement;
- if (!el || !this.chat.hasMoreHistory()) return;
- this.loadingEarlier = true;
- const beforeHeight = el.scrollHeight;
- const beforeTop = el.scrollTop;
- try {
- await this.chat.paginate();
- // 等两帧:一帧提交 DOM、一帧完成布局(图片/表格撑高)
- await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(null))));
- const after = this.scroller()?.nativeElement;
- if (after) {
- after.scrollTop = beforeTop + (after.scrollHeight - beforeHeight);
- }
- } finally {
- this.loadingEarlier = false;
- }
- }
- /**
- * 首屏不满一屏且还有更早消息时自动补齐(最多 3 轮)。
- * 否则用户看到内容没填满、却没有可滚动空间,永远触发不到「触顶加载」。
- *
- * 🔴 新建态不补齐(2026-11-08):新建会话本来就没有更早的消息,
- * 而 `hasMoreHistory` 取自房间级 token —— 不挡就会自动翻出整个房间的旧历史。
- */
- private async fillViewportIfNeeded(): Promise<void> {
- if (this.chat.state() === 'empty') return;
- for (let i = 0; i < 3; i++) {
- const el = this.scroller()?.nativeElement;
- if (!el || !this.chat.hasMoreHistory()) return;
- if (el.scrollHeight > el.clientHeight + 8) return;
- await this.loadEarlier();
- }
- }
- protected back(): void {
- void this.router.navigateByUrl('/mobile/messages');
- }
- /**
- * 任务深链(2026-11-11 改)。
- *
- * 「任务」页路由已下线(用户裁决:入口和路由一起关),原来跳
- * `/mobile/tasks/:id` 会落到消息列表,用户以为点坏了。
- * 改为**留在当前页**:关掉抽屉、打开成果/状态抽屉的任务页,并高亮该条。
- */
- protected goTask(id: string): void {
- this.sheetTab.set('task');
- this.railHighlight.set(id);
- this.sheetOpen.set(true);
- if (this.railHighlightTimer) clearTimeout(this.railHighlightTimer);
- this.railHighlightTimer = setTimeout(() => this.railHighlight.set(null), 2000);
- }
- /** 试用到期提示条的「去开通」:回套餐页(2026-12-03) */
- protected goPlan(): void {
- void this.router.navigateByUrl('/plans');
- }
- /**
- * 打开文件预览(2026-11-03)。
- *
- * 与 PC 端 `openFile()` 同口径:按类型分流 —— 图片进灯箱,其余进通用预览器。
- * 原实现用 `window.open` 新开标签页,移动端体验割裂(离开 App、失去返回路径)。
- */
- protected openFile(f: {
- name: string;
- url?: string;
- cloudUrl?: string;
- mimeType?: string;
- size?: number;
- }): void {
- /*
- * 🔴 优先用云盘链接(2026-11-13 用户实测反馈):
- * `url` 可能是本地 blob(刷新即失效)或 Matrix 媒体地址(需要 blob 中转、
- * Safari 兼容差);`cloudUrl` 才是长期可访问、能直接打开的云盘链接。
- */
- const url = f.cloudUrl || f.url;
- if (!url) return;
- const mime = f.mimeType ?? '';
- if (previewKindOf(f.name || url, mime) === 'image') {
- this.lightbox.set({ url, name: f.name, size: f.size ?? 0 });
- return;
- }
- this.preview.set({ url, name: f.name, mimeType: mime });
- }
- protected taskTone(t: Task): BadgeTone {
- return TASK_TONE[t.status] ?? 'neutral';
- }
- protected taskText(t: Task): string {
- return TASK_STATUS_TEXT[t.status] ?? t.status;
- }
- private scrollToBottom(): void {
- const el = this.scroller()?.nativeElement;
- if (el) el.scrollTop = el.scrollHeight;
- }
- /**
- * 贴底(2026-11-10,与桌面端 `stickToBottom` 同口径)。
- *
- * · 用户主动上翻 → 不拽回
- * · 正在加载更早消息 → 不贴底(那是往上插入)
- * · 200ms 节流:流式输出时每帧都在长高,不节流会和渲染抢主线程
- * · 补一次 rAF + 一次延时:图片 / Markdown 异步渲染后高度还会变
- */
- private stickToBottom(): void {
- if (this.userScrolledAway) return;
- if (this.loadingEarlier) return;
- const now = Date.now();
- if (now - this.lastStickAt < 200) return;
- this.lastStickAt = now;
- queueMicrotask(() => this.scrollToBottom());
- requestAnimationFrame(() => {
- this.scrollToBottom();
- setTimeout(() => this.scrollToBottom(), 120);
- });
- }
- }
- /** 渲染行的时间戳(用于按时间排序) */
- function keyTs(r: MessageRow): number {
- const ts = (m?: Message): number => (m ? Date.parse(m.ts) || 0 : 0);
- if (r.kind === 'msg') return ts(r.message);
- if (r.kind === 'turn') {
- for (const b of r.blocks) {
- if (b.kind === 'msg') return ts(b.message);
- }
- }
- return 0;
- }
- /**
- * 两组成果的 id 序列是否完全相同(2026-11-13 请求风暴防线)。
- *
- * 与桌面端 `sameIds` 同口径:内容没变就不写新数组,
- * 避免无意义唤醒下游 computed / effect。
- */
- function sameDeliverableIds(
- a: readonly Deliverable[],
- b: readonly Deliverable[],
- ): boolean {
- if (a.length !== b.length) return false;
- for (let i = 0; i < a.length; i++) if (a[i].id !== b[i].id) return false;
- return true;
- }
|