import { ChangeDetectionStrategy, Component, computed, effect, ElementRef, inject, signal, viewChild, } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { UiAlert, UiAvatar, UiButton, UiEmpty, UiInput, UiModal, UiSkeleton, UiTooltip, } from '../../../ui'; import { ComposerComponent } from '../../../components/domain/composer/composer'; import { NewSessionRequest } from '../../../components/domain/session-tree/session-tree'; import { MessageBubbleComponent } from '../../../components/domain/message-bubble/message-bubble'; import { TypingIndicatorComponent } from '../../../components/domain/typing-indicator/typing-indicator'; import { ToolActivityComponent } from '../../../components/domain/tool-activity/tool-activity'; import { FilePreviewComponent } from '../../../components/preview/file-preview/file-preview'; import { NewSessionModalService } from '../../../components/domain/new-session-modal/new-session-modal.service'; import { ImageLightboxComponent } from '../../../components/preview/image-lightbox/image-lightbox'; import { previewKindOf, type PreviewKind } from '../../../components/preview/file-kind'; import { PresenceBadgeComponent } from '../../../components/domain/presence-badge/presence-badge'; import { AgentPresence, agentPresence } from '../../../core/api/models'; import { StatusBadgeComponent } from '../../../components/domain/status-badge/status-badge'; import { ChatService } from '../../../core/chat.service'; import { Deliverable, TASK_STATUS_TEXT } from '../../../core/api/models'; import { DeliverablesService } from '../../../core/deliverables.service'; import { DeviceService } from '../../../core/device.service'; import { fmtPercent, fmtTokens, usageOf } from '../../../core/format'; import { TaskLine, TaskPulseService } from '../../../core/task-pulse.service'; import { ArtifactSyncService } from '../../../core/artifact-sync.service'; import { LoopGuardService } from '../../../core/loop-guard.service'; import { isToolActivityMessage, toolActivitySummary } from '../../../core/message-segments'; import { Block } from '../../../core/message-segments'; import { Message } from '../../../core/api/models'; import { fmtTime } from '../../../core/time'; import { LiveService } from '../../../core/live.service'; import { UnreadService } from '../../../core/unread.service'; import { TasksService } from '../../../core/tasks.service'; import { ChatSession } from '../../../core/chat-session'; import { ChatSessionService } from '../../../core/chat-session.service'; import { MatrixSessionService } from '../../../core/matrix-session.service'; import { WorkspaceService } from '../../../core/workspace.service'; import { AgentModalService } from '../../../components/domain/agent-modal/agent-modal.service'; /** * 桌面·会话(SPEC FR-04)—— 四栏(导航 + 会话列表 + 聊天区 + 成果栏) * * 实现纪律(2026-10-15 返工): * · 列表/空态/加载/提示条全部走底座组件(`ui-list` / `ui-empty` / `ui-skeleton` / `ui-alert`) * · **流动布局**:栏宽用比例 + 最小宽兜底,窗口变宽时主区跟着变宽; * 仅当可用宽不足以容纳右栏时才降级(换形态,不删功能) * · 无 demo 件 * * AC:04.1 四栏 / 04.2 发送 / 04.3 上传进度 / 04.5 自增高 / 04.6 状态不重复 * / 04.8 失败可重试 / 04.9 连接状态 / 04.10 超长截断 / 04.11 三态 */ /** 一条消息的渲染形态:普通气泡 or 终端活动折叠组 */ type MessageRow = | { kind: 'msg'; key: string; message: Message } | { kind: 'tool'; key: string; block: Extract }; /** 右栏标签 */ export type RailTab = 'tasks' | 'files' | 'results' | 'status'; /** 读上次选中的右栏标签(按用户隔离的 localStorage) */ function readRailTabPref(): RailTab { try { const v = localStorage.getItem('fmode_rail_tab'); if (v === 'tasks' || v === 'files' || v === 'results' || v === 'status') return v; } catch { /* 隐私模式 */ } // 默认「文件」:用户最关心本次对话产出了什么 return 'files'; } /** * 右栏宽度夹取 —— **纯函数**,便于单测。 * * 下限 280:再窄右栏里「文件名 + 大小」会折行成两三行; * 上限 560:再宽就把对话区挤到不可读(主区最小可读宽约 480)。 */ export function clampRailWidth(w: number): number { if (!Number.isFinite(w)) return 320; return Math.min(560, Math.max(280, Math.round(w))); } /** * 预览形态下的右栏宽度上限(2026-10-30)。 * 看文档/表格时 560px 太窄;预览打开时放宽到 720,关闭后回到常规上限。 */ export const RAIL_W_PREVIEW_MAX = 720; export function clampPreviewRailWidth(w: number): number { return Math.min(RAIL_W_PREVIEW_MAX, Math.max(280, Math.round(Number.isFinite(w) ? w : 320))); } /** 左栏「容器行」—— 会话按容器分组时的分组头 */ interface ConversationRow { id: string; name: string; specialty?: string; currentTask?: string; unread?: number; } @Component({ selector: 'app-dk-chat-page', changeDetection: ChangeDetectionStrategy.OnPush, imports: [ UiAlert, UiAvatar, UiButton, UiEmpty, UiInput, UiModal, UiSkeleton, UiTooltip, ComposerComponent, MessageBubbleComponent, TypingIndicatorComponent, ToolActivityComponent, FilePreviewComponent, ImageLightboxComponent, PresenceBadgeComponent, StatusBadgeComponent, ], template: `
@if (!chat.agentId()) {
} @else {
@if (chat.agent(); as a) {
{{ a.name }} @if (chat.currentSession(); as s) { {{ s.title }} @if (s.archived) { 已归档 } } @else { {{ a.specialty || '数字生命' }} }
@if (a.status === 'error' || a.status === 'offline' || a.status === 'stopped') { } } @if (chat.agent(); as a) { @if (taskLine(a.id).text) { {{ taskLine(a.id).text }} } }
@if (chat.agentId(); as aid) { }
@if (chat.connection() !== 'connected' || currentContainerState() === 'unreported') { } @if (loop.paused()) { }
@switch (chat.state()) { @case ('loading') {
@for (i of [1, 2, 3]; track i) { }
} @case ('error') {
重新加载
} @case ('empty') { @if (!chat.currentSession()) { @if (chat.pendingNewSession()) {

{{ greeting() }},我是 {{ chat.agent()?.name ?? '你的数字生命' }}

直接输入第一条消息,就会开始这段对话。

@for (s of suggests; track s.title) { }
} @else {

还没有对话

点击左侧「新建对话」,选择一个数字生命后开始。

新建对话
} } @else {

{{ greeting() }},我是 {{ chat.agent()?.name ?? '你的数字生命' }}

{{ chat.agent()?.specialty || '把要做的事直接说给我,我来干。' }}

@for (s of suggests; track s.text) { }
} } @default {
@if (chat.paginating()) { } @else if (chat.hasMoreHistory()) { 加载更早的消息 } @else { 已到最早 }
@for (row of messageRows(); track row.key) { @if (row.kind === 'tool') { } @else { } } @if (chat.peerTyping()) {
} } }
@if (chat.currentSession() || chat.pendingNewSession()) {
@if (chat.pendingFiles().length > 0) {
@for (pf of chat.pendingFiles(); track pf.id) { @if (pf.previewUrl) {
} @else { {{ pf.file.name }} } }
}
} }
@if (chat.agentId() && railOpen()) { }

容器还在把文件搬到云盘,完成后可以在右栏「成果」里直接预览。

@if (mediaFile(); as mf) { @if (mediaKind(mf) === 'video') { } @else { } }

仅从左侧列表移除「{{ removing()?.title }}」。
消息内容不会被删除,仍在服务器上。

取消 移除
`, styles: [ ` @use '../../../core/styles/breakpoints' as bp; :host { display: block; height: 100%; /* 参与父级网格时,默认的 min-height:auto 会被内容撑高 → 整页滚动 */ min-height: 0; overflow: hidden; } /* * 拖动右栏宽度期间禁止选中文本 —— 否则鼠标划过整页文字全被刷蓝。 * 用 :host-context 而不用全局样式:只在会话页生效,且不必动 styles.scss * (那里有行数预算,2026-10-30 已经顶到 300 行)。 */ :host-context(body.is-resizing-rail) { user-select: none; cursor: col-resize; } /* 四栏:列表固定可读宽(min~max),主区吃掉全部剩余,右栏按比例但设上下限。 —— 窗口变宽时主区跟着变宽(不是内容整体缩放),这是"流动布局"的要点。 */ /* 列表栏用**固定可读宽**(280px)而非比例:列表项是纵向排列, 宽度随窗口缩放会把名字/预览压到不可读。右栏才用比例。 */ /* 列数随右栏显隐**动态变化** —— 否则右栏隐藏后那一列仍占位,聊天区不填满。 用 :has() 检测 .rail-col 是否存在(存在才保留第三列)。 */ .conversation-layout { display: grid; grid-template-columns: minmax(0, 1fr); height: 100%; min-height: 0; } /* * 有右栏时是三列:主区 | 拖宽手柄(5px) | 右栏。 * 右栏宽度由 JS 写到 inline style,这里只给 1fr 之外的兜底 —— * 🔴 列数必须把 resizer 算进去,否则右栏会被挤到下一行(实测:掉到内容下方)。 */ .conversation-layout:has(> .rail-col) { grid-template-columns: minmax(0, 1fr) 5px var(--rail-w, 320px); } /* * 窄窗(<1150)压缩右栏宽度,但**不让它换行**(2026-10-30 用户要求)。 * * 🔴 原实现把栅格改成单列 + 隐藏右栏;一旦隐藏规则因为任何原因没生效 * (选择器优先级、样式加载顺序),右栏就会掉到主区**下方**, * 表现为"右栏跑到页面底部"(实测现象)。 * 现在的做法:列数恒定三列,只把第三列压到 280px 下限, * 从结构上排除"掉到下方"的可能。 */ @include bp.dk-below-4col { .conversation-layout:has(> .rail-col) { grid-template-columns: minmax(0, 1fr) 5px minmax(240px, var(--rail-w, 320px)); } } .col { min-width: 0; min-height: 0; display: flex; flex-direction: column; background: var(--surface); } .main-col { background: var(--surface); border-right: 1px solid var(--edge); } .rail-col { background: var(--rail-surface); /* 宽度来自栅格列(--rail-w 由容器上的 inline 变量传入) */ min-width: 0; display: flex; flex-direction: column; overflow: hidden; } /* ---- 拖宽手柄 ---- */ .rail-resizer { position: relative; width: 5px; z-index: 2; cursor: col-resize; flex-shrink: 0; background: transparent; transition: background-color var(--motion-fast) var(--ease-standard); } /* 热区左右各扩 3px:5px 的线太细,很难点中 */ .rail-resizer::after { content: ''; position: absolute; inset: 0 -3px; } .rail-resizer:hover, .rail-resizer:active { background: var(--primary); } .rail-resizer:focus-visible { outline: 2px solid var(--primary); outline-offset: -1px; } /* ---- 右栏标题行 ---- */ /* ---- 右栏内联预览 ---- */ /* * 预览时 rail-body 不滚动、不留内边距(2026-10-31): * rail-body 的滚动容器 + 预览面板的 100% 高度叠加,在浏览器整体缩放后 * 会把底部状态栏挤出可视区(用户截图)。预览面板内部自己滚动即可。 */ .rail-body.has-preview { padding: 0; overflow: hidden; /* flex 列:让 .rail-preview 撑满,而不是按内容塌缩(block 下子元素无高度) */ display: flex; flex-direction: column; gap: 0; align-content: normal; } .rail-preview { display: flex; flex-direction: column; flex: 1; min-height: 0; overflow: hidden; } /* 音视频模态 */ .media-modal-el { display: block; width: 100%; max-height: 70dvh; border-radius: var(--r-sm); background: var(--surface-2); } .media-modal-el--audio { max-height: none; } .rail-preview app-file-preview { /* flex 链而非 display:block:块级宿主会按内容塌缩(实测面板高度随缩放变化) */ flex: 1 1 0; min-height: 0; overflow: hidden; } /* 预览期间隐藏标签条 —— 已经在看具体文件了,切标签会让预览莫名消失 */ .rail-col:has(.rail-preview) .rail-tabs { display: none; } .rail-head { display: flex; align-items: center; gap: var(--sp-2); padding: var(--sp-3) var(--sp-3) var(--sp-2); flex-shrink: 0; } .rail-head-ico { display: grid; place-items: center; width: 28px; height: 28px; flex-shrink: 0; border-radius: var(--r-sm); background: var(--surface-hover); color: var(--ink-2); font-size: var(--fs-12); } .rail-head-text { display: grid; gap: 1px; flex: 1; min-width: 0; line-height: 1.35; } .rail-head-text strong { font-size: var(--fs-13); font-weight: 600; color: var(--ink); } .rail-head-text small { font-size: var(--fs-11); color: var(--muted); } .col-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: var(--sp-4); border-bottom: 1px solid var(--edge); } .col-head h2 { margin: 0; font-size: var(--fs-15); color: var(--ink); } .count { font-size: var(--fs-11); color: var(--muted); } .search-hold { padding: var(--sp-3) var(--sp-4); } .list-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 0 var(--sp-2) var(--sp-3); } .skeleton-hold { display: grid; gap: var(--sp-2); padding: var(--sp-2); } .center { display: flex; justify-content: center; padding: var(--sp-3); } .center-fill { flex: 1; display: grid; place-content: center; } /* 会话行:与容器行缩进错开,一眼看出层级 */ .session-row { display: flex; align-items: center; gap: var(--sp-2); min-height: 40px; margin-left: var(--sp-6); padding: var(--sp-1) var(--sp-2) var(--sp-1) var(--sp-3); border-radius: var(--r-md); cursor: pointer; } .session-row:hover { background: var(--surface-hover); } .session-row.active { background: var(--surface-active); } .session-row.archived .session-title { color: var(--faint); text-decoration: line-through; } .session-title { flex: 1; min-width: 0; font-size: var(--fs-13); color: var(--ink-2); } .session-row.active .session-title { color: var(--ink); font-weight: 600; } .session-time { flex: none; font-size: var(--fs-11); color: var(--faint); } /* * 操作按钮默认隐藏,悬停或键盘聚焦时出现 —— 列表平时保持安静, * 但**不能只靠 hover**:触屏与键盘用户拿不到,所以 :focus-within 也触发。 */ .session-acts { display: none; align-items: center; gap: 2px; } .session-row:hover .session-acts, .session-row:focus-within .session-acts { display: flex; } /* 操作按钮出现时让位,避免标题被挤成一两个字 */ .session-row:hover .session-time, .session-row:focus-within .session-time { display: none; } /* 移除确认弹窗 */ .remove-note { margin: 0; font-size: var(--fs-13); line-height: 1.6; color: var(--ink-2); } .remove-acts { display: flex; justify-content: flex-end; gap: var(--sp-2); margin-top: var(--sp-4); } /* ---------- 空会话欢迎区(2026-10-29,参考 ChatGPT 落地页) ---------- */ .welcome { display: grid; place-items: center; min-height: 100%; padding: var(--sp-6) var(--sp-4); } .welcome-inner { display: grid; justify-items: center; gap: var(--sp-3); width: 100%; max-width: 620px; text-align: center; } .welcome-title { margin: var(--sp-2) 0 0; font-size: var(--fs-20); font-weight: 600; color: var(--ink); line-height: 1.3; } .welcome-sub { margin: 0; max-width: 460px; font-size: var(--fs-14); color: var(--muted); line-height: 1.7; } .suggests { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--sp-2); width: 100%; margin-top: var(--sp-3); } /* 窄窗单列:两列会把标题压成一行省略号,信息全丢 */ @include bp.dk-below-3col { .suggests { grid-template-columns: minmax(0, 1fr); } } .suggest { display: flex; align-items: center; gap: var(--sp-3); min-height: var(--touch-min); padding: var(--sp-3); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface); text-align: left; cursor: pointer; transition: background-color var(--motion-fast) var(--ease-standard); } .suggest:hover { background: var(--surface-hover); border-color: var(--edge-strong); } .suggest > i { flex-shrink: 0; width: 16px; text-align: center; color: var(--primary); } .suggest-text { display: grid; min-width: 0; gap: 2px; } .suggest-text strong { font-size: var(--fs-13); font-weight: 600; color: var(--ink); } .suggest-text small { font-size: var(--fs-12); color: var(--muted); } /* ---------- 新建对话:选容器模态框(D3) ---------- */ .pick-note { margin: 0 0 var(--sp-3); font-size: var(--fs-13); color: var(--muted); line-height: 1.7; } .pick-list { display: grid; gap: var(--sp-1); max-height: 360px; overflow-y: auto; } .pick-row { display: flex; align-items: center; gap: var(--sp-3); min-height: var(--touch-min); padding: var(--sp-2) var(--sp-3); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface); text-align: left; cursor: pointer; } .pick-row:hover { background: var(--surface-hover); border-color: var(--edge-strong); } .pick-row:focus-visible { outline: 2px solid var(--primary); outline-offset: -2px; } .pick-text { display: grid; min-width: 0; line-height: 1.3; } .pick-name { font-size: var(--fs-13); font-weight: 600; color: var(--ink); } .pick-sub { font-size: var(--fs-11); color: var(--muted); } .pick-empty { margin: 0; padding: var(--sp-4); font-size: var(--fs-13); color: var(--muted); text-align: center; } .pick-acts { display: flex; justify-content: flex-end; margin-top: var(--sp-3); } /* 无会话空态(2026-11-01):提示先新建对话,不自动建空会话 */ .no-session { display: grid; justify-items: center; gap: var(--sp-3); padding: var(--sp-8) var(--sp-4); text-align: center; color: var(--muted); } .no-session > i { font-size: var(--fs-26); color: var(--edge-strong, var(--muted)); } .no-session-title { margin: 0; font-size: var(--fs-15); color: var(--ink); } .no-session-sub { margin: 0; font-size: var(--fs-13); } /* 已归档目录 */ /* 待发送附件条 */ .pending-holds { display: flex; flex-wrap: wrap; gap: var(--sp-2); padding: var(--sp-2) 0; } /* 输入区与消息流同宽:宽屏下居中,窄屏贴边留 16px */ /* 正在输入指示器:作为消息流的**最后一行**出现(2026-11-01)。 与消息气泡同样的居中限宽,让它看起来就是「即将到来的这一条」, 而不是浮在输入框上方的独立提示。 */ .typing-row { display: flex; align-items: flex-start; margin-bottom: var(--sp-4); } .composer-hold { flex-shrink: 0; padding: 0 max(var(--sp-4), calc((100% - 768px) / 2)); } .pending-chip { display: inline-flex; align-items: center; gap: var(--sp-2); max-width: 220px; padding: var(--sp-1) var(--sp-2); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface-2); font-size: var(--fs-12); color: var(--ink-2); } .pending-thumb { width: 32px; height: 32px; border-radius: var(--r-sm); object-fit: cover; flex: none; background: var(--surface-2); } /* 图片待发送卡片:缩略图铺满,操作条压底部,右上角移除 */ .pending-card { position: relative; width: 132px; height: 96px; border-radius: var(--r-md); overflow: hidden; background: var(--surface-2); box-shadow: var(--shadow-soft, none); } .pending-card-img { display: block; width: 100%; height: 100%; padding: 0; border: 0; background: none; cursor: zoom-in; object-fit: cover; } .pending-card-act { position: absolute; left: 0; right: 0; bottom: 0; display: flex; align-items: center; min-height: 26px; padding: 0 var(--sp-2); font-size: var(--fs-11); color: var(--inverse); background: color-mix(in srgb, var(--canvas) 62%, transparent); backdrop-filter: blur(2px); white-space: nowrap; pointer-events: none; } .pending-x--float { position: absolute; top: 4px; right: 4px; border-radius: var(--r-tag); background: color-mix(in srgb, var(--canvas) 60%, transparent); color: var(--inverse); opacity: 0; transition: opacity var(--motion-fast) var(--ease-standard); } .pending-card:hover .pending-x--float, .pending-card:focus-within .pending-x--float { opacity: 1; } .pending-name { min-width: 0; } .pending-x { display: grid; place-items: center; flex: none; width: 20px; height: 20px; border: 0; border-radius: var(--r-sm); background: transparent; color: var(--faint); cursor: pointer; } .pending-x:hover { background: var(--surface-hover); color: var(--ink); } .archived-toggle { display: flex; align-items: center; gap: var(--sp-2); width: calc(100% - var(--sp-6)); margin-left: var(--sp-6); min-height: 32px; padding: var(--sp-1) var(--sp-2) var(--sp-1) var(--sp-3); border: 0; border-radius: var(--r-md); background: transparent; font: inherit; font-size: var(--fs-12); color: var(--faint); cursor: pointer; } .archived-toggle:hover { background: var(--surface-hover); color: var(--muted); } .archived-toggle:focus-visible { outline: 2px solid var(--primary); outline-offset: -2px; } .archived-toggle i { width: 12px; font-size: var(--fs-10); } .archived-count { padding: 0 6px; border-radius: 999px; background: var(--surface-2); font-size: var(--fs-11); } .session-empty { margin-left: var(--sp-6); padding: var(--sp-2) var(--sp-3); font-size: var(--fs-12); color: var(--faint); } /* 头部:当前任务名(只读,2026-10-31 取消改名) */ .preview-pending-hint { margin: 0; color: var(--ink-2); font-size: var(--fs-13); line-height: 1.6; } .session-name { display: inline-flex; align-items: center; gap: var(--sp-1); cursor: default; } .session-name:hover { color: var(--ink-2); } .archived-tag { margin-left: var(--sp-1); padding: 0 var(--sp-1); border-radius: var(--r-sm); background: var(--surface-2); color: var(--faint); font-size: var(--fs-11); } .conv-info { display: grid; gap: 2px; flex: 1; min-width: 0; } .conv-line { display: flex; align-items: center; gap: var(--sp-2); } .conv-line strong { font-size: var(--fs-15); color: var(--ink); } /* 预览操作区:多个附件时按钮带文件名,过长截断 */ .preview-actions { display: flex; flex-wrap: wrap; gap: var(--sp-2); margin-top: var(--sp-3); } .download { display: inline-flex; align-items: center; gap: var(--sp-1); max-width: 240px; min-height: var(--touch-min); padding: 0 var(--sp-3); border-radius: var(--r-sm); background: var(--primary); color: var(--primary-content); font-size: var(--fs-13); text-decoration: none; } .dl-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .conv-preview { font-size: var(--fs-12); color: var(--muted); } /* 第二行:任务描述占满剩余宽度,接入态徽标靠右不换行 */ .conv-subline { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; } .conv-task { flex: 1; min-width: 0; font-size: var(--fs-12); color: var(--muted); } .unread { min-width: 18px; padding: 0 5px; border-radius: var(--r-tag); background: var(--danger); color: var(--on-danger); font-size: var(--fs-11); line-height: 18px; text-align: center; flex-shrink: 0; } /* 头部两行:① 头像 + 名称 + 状态徽标 + 操作 ② 当前任务整行。 用 grid 显式分行,任务名再长也不会挤压头像/标题(此前挤成一排)。 */ /* * 标题栏(2026-10-29):**单行**,高度 56px 与顶部导航一致。 * 原来是「头像/标题/状态/操作」+「任务状态独占一行」的两行网格 —— * 多出来的那一行把整个消息区往下推,观感上就是"顶部被抬高了"。 * 现在任务状态并入标题行右侧,作为紧凑标签。 */ .chat-head { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto auto; grid-template-areas: 'avatar title task status actions'; align-items: center; column-gap: var(--sp-3); /* * 🔴 固定高度而不是 min-height:内容变化(任务状态出现/消失)不得改变栏高, * 否则下方消息区会跟着位移 —— 用户看到的"发送时跳动"。 */ height: var(--desk-topbar-h); padding: 0 var(--sp-4); border-bottom: 1px solid var(--edge); } /* 任务状态槽位:定宽定高,内部截断 */ .task-slot { display: flex; align-items: center; min-width: 0; max-width: 220px; height: 100%; } .chat-head > ui-avatar { grid-area: avatar; } .chat-head > .chat-title { grid-area: title; } .chat-head > .task-line { grid-area: task; } /* 🔴 徽标与操作区各占一格 —— 曾经共用 status 格,操作按钮把徽标压住了 */ .chat-head > app-status-badge { grid-area: status; justify-self: end; } .chat-head > .chat-actions { grid-area: actions; justify-self: end; } .chat-head > .task-line { grid-area: task; } .chat-title { display: grid; gap: 2px; flex: 1; min-width: 0; } .chat-title strong { font-size: var(--fs-15); color: var(--ink); } .chat-title small { font-size: var(--fs-12); color: var(--muted); } .chat-actions { display: flex; gap: var(--sp-1); } /* 当前任务整行:一个会话一屏只出现一次「它在做什么」。 左侧细色条 + 会转的小点表达「正在做」,完成态不转。 用整行而非胶囊:任务描述通常较长,胶囊装不下只能省略。 */ .task-line { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; max-width: 100%; padding: var(--sp-1) var(--sp-2); border-radius: var(--r-sm); font-size: var(--fs-12); color: var(--muted); } .task-line .spin { width: 8px; height: 8px; flex-shrink: 0; border-radius: 50%; background: var(--muted); } .task-line.busy .spin { background: var(--success); animation: pulse-dot 1.4s var(--ease-standard) infinite; } .task-line.tone-warning { color: var(--warning); } .task-line.tone-warning .spin { background: var(--warning); } .task-line.tone-danger { border-left-color: var(--danger); color: var(--danger); } .task-line.tone-danger .spin { background: var(--danger); } .task-line.tone-success, .task-line.tone-info { border-left-color: var(--success); color: var(--success); } .task-line.tone-success .spin, .task-line.tone-info .spin { background: var(--success); } @keyframes pulse-dot { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.35; transform: scale(0.8); } } @media (prefers-reduced-motion: reduce) { .task-line.busy .spin { animation: none; } } /* 运行态小标签:圆点 + 文字(不用底色块,避免标题行三个彩色块打架)。 只有「执行中」的圆点会呼吸,其余是静态灰/黄点。 */ .run-chip { display: inline-flex; align-items: center; gap: 4px; flex-shrink: 0; font-size: var(--fs-11); color: var(--muted); white-space: nowrap; } .run-chip .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--edge-strong); } .run-chip.tone-success .dot, .run-chip.tone-info .dot { background: var(--success); } .run-chip.tone-success, .run-chip.tone-info { color: var(--success); } .run-chip.tone-success .dot, .run-chip.tone-info .dot { animation: pulse-dot 1.4s var(--ease-standard) infinite; } .run-chip.tone-warning { color: var(--warning); } .run-chip.tone-danger { color: var(--danger); } .run-chip.tone-danger .dot { background: var(--danger); } .run-chip.tone-warning .dot { background: var(--warning); } @media (prefers-reduced-motion: reduce) { .run-chip .dot { animation: none !important; } } /* 最近动态 */ .pulse-list { margin: 0; padding: 0; list-style: none; display: grid; gap: var(--sp-2); } .pulse-item { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; font-size: var(--fs-12); color: var(--ink-2); } .pulse-item i { width: 12px; flex-shrink: 0; color: var(--muted); font-size: var(--fs-11); } .pulse-text { flex: 1; min-width: 0; } .pulse-item small { flex-shrink: 0; color: var(--muted); font-size: var(--fs-11); } .tone-ink-success { color: var(--success); } .tone-ink-warning { color: var(--warning); } /* 右栏切换按钮的激活态 */ .chat-actions ui-button.on button { background: var(--primary-subtle); color: var(--primary); } .rail-item.task .task-ico { background: var(--info-subtle); color: var(--info); } .rail-item > i { color: var(--muted); flex-shrink: 0; } .loop-detail { margin: 0 0 var(--sp-1); font-size: var(--fs-12); color: var(--ink-2); } .loop-hint { margin: 0 0 var(--sp-2); font-size: var(--fs-12); color: var(--muted); } .banner-hold { padding: var(--sp-3) var(--sp-4) 0; } /* * 消息流(2026-10-29 对照 ChatGPT demo 重做): * · **居中限宽 768px** —— 原实现撑满整列,宽屏下长段落一行 1200px+, * 眼睛横跨屏幕读字极累;聊天类界面的阅读宽度上限是硬需求。 * · 间距 20px —— 原来 12px,相邻两块回复几乎粘在一起,分不清是两条消息。 * · 用 padding 让出左右留白,而不是给每个气泡加 margin(否则限宽容器跟着缩)。 */ .messages { flex: 1; min-height: 0; /* * 🔴 必须同时锁横向:只写 overflow-y:auto 时,x 轴默认是 visible → * 任一子元素(长 URL、宽表格、文件卡片)撑出宽度就会冒出横向滚动条 * (用户实测:消息区底部出现一条横条)。 * 内容自身负责换行/裁剪(见 message-bubble 的 overflow-wrap)。 */ overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; display: grid; /* 消息间距 20 → 24(对齐参考实现的 ~28px 密度),条与条之间更容易分辨 */ gap: var(--sp-6); align-content: start; /* 上下留白加大:滚到底时最后一条不贴着输入框 */ padding: var(--sp-6) max(var(--sp-4), calc((100% - 768px) / 2)) var(--sp-8); } /* 顶部历史区 / 空态 / 骨架屏不吃限宽偏移,保持整列居中 */ .messages > .history-hold, .messages > .center, .messages > .skeleton-hold, .messages > .welcome { width: 100%; max-width: 768px; margin-inline: auto; } /* AC-04.4:历史加载区(顶部) */ .history-hold { display: flex; justify-content: center; padding: var(--sp-1) 0; } .history-end { font-size: var(--fs-12); color: var(--muted); } /* ---------- 右栏标签条(四标签,一个标签一件事) ---------- */ .rail-tabs { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 2px; padding: var(--sp-2) var(--sp-2) 0; border-bottom: 1px solid var(--edge); flex-shrink: 0; } .rail-tab { display: inline-flex; align-items: center; justify-content: center; gap: var(--sp-1); min-height: 36px; padding: 0 var(--sp-1); border: 0; border-bottom: 2px solid transparent; background: transparent; font: inherit; font-size: var(--fs-12); color: var(--muted); cursor: pointer; white-space: nowrap; } .rail-tab:hover { color: var(--ink-2); background: var(--surface-hover); } .rail-tab.on { color: var(--ink); border-bottom-color: var(--primary); font-weight: 600; } .rail-tab:focus-visible { outline: 2px solid var(--primary); outline-offset: -2px; } .rail-tab i { font-size: var(--fs-11); } .rail-tab-count { padding: 0 5px; border-radius: 999px; background: var(--surface-2); font-size: var(--fs-11); font-weight: 400; color: var(--muted); } .rail-body { flex: 1; min-height: 0; overflow-y: auto; padding: var(--sp-4); display: grid; gap: var(--sp-5); align-content: start; } .rail-block h3 { display: flex; align-items: center; gap: var(--sp-2); margin: 0 0 var(--sp-3); font-size: var(--fs-13); color: var(--ink-2); } .kv { margin: 0; display: grid; gap: var(--sp-2); } .kv > div { display: flex; justify-content: space-between; gap: var(--sp-3); font-size: var(--fs-12); } .kv dt { color: var(--muted); flex-shrink: 0; } .kv dd { margin: 0; color: var(--ink); text-align: right; min-width: 0; overflow-wrap: anywhere; } .rail-empty { margin: 0; font-size: var(--fs-12); color: var(--muted); } .rail-item { display: flex; align-items: center; gap: var(--sp-3); width: 100%; min-height: var(--touch-min); padding: var(--sp-2); margin-bottom: var(--sp-2); border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface); text-align: left; cursor: pointer; } .rail-item:hover { background: var(--surface-hover); } .file-icon { display: grid; place-items: center; width: 32px; height: 32px; flex-shrink: 0; border-radius: var(--r-sm); background: var(--info-subtle); color: var(--info); } .rail-meta { display: grid; gap: 2px; min-width: 0; flex: 1; } .sync-hint { display: inline-flex; align-items: center; gap: var(--sp-1); color: var(--muted); } .rail-meta strong { font-size: var(--fs-13); color: var(--ink); } .rail-meta small { font-size: var(--fs-11); color: var(--muted); } .ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } `, ], }) export class DkChatPage { readonly chat = inject(ChatService); readonly live = inject(LiveService); /** 重连时重建常驻 Matrix 连接(登出/断线后需要) */ private readonly matrixSession = inject(MatrixSessionService); private readonly unread = inject(UnreadService); private readonly deliverables = inject(DeliverablesService); private readonly tasks = inject(TasksService); private readonly pulse = inject(TaskPulseService); private readonly artifactSync = inject(ArtifactSyncService); readonly loop = inject(LoopGuardService); /** 多会话(线程)—— 左栏会话列表的唯一数据源 */ readonly sessions = inject(ChatSessionService); private readonly workspaceSvc = inject(WorkspaceService); private readonly agentModal = inject(AgentModalService); private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); private readonly device = inject(DeviceService); readonly keyword = signal(''); /** * 新建对话时选定的工作区(D3 模态框)。 * `undefined` = 未打开;`null` = 日常对话;`string` = 工作区 id。 */ readonly newSessionWorkspace = signal(undefined); /** 「新建对话」模态框(左栏按钮与空态引导共用) */ private readonly newSessionModal = inject(NewSessionModalService); /** 空态里点「新建对话」→ 打开容器选择框 */ requestNewSession(): void { this.newSessionModal.open(null); } readonly railOpen = signal(true); /** 右栏内联预览的成果 */ readonly previewing = signal(null); /** 右栏当前面板:任务 / 成果 */ /** * 右栏当前标签。 * * 四个标签各管一件事(参考 DSH 右栏): * 任务 = 该容器的任务 / 文件 = 本会话产出的文件 / * 成果 = 平台上报的交付成果 / 状态 = 运行状态与最近动态 * * 默认「文件」—— 用户最关心「这次对话产出了什么」。 */ readonly railTab = signal(readRailTabPref()); /** 标签定义(模板遍历用,避免在模板里重复写四份) */ readonly railTabs: { key: RailTab; label: string; icon: string; hint: string }[] = [ { key: 'tasks', label: '任务', icon: 'fa-list-check', hint: '该容器名下的任务' }, { key: 'files', label: '文件', icon: 'fa-paperclip', hint: '本次对话产出的文件' }, { key: 'results', label: '成果', icon: 'fa-box', hint: '平台上报的交付成果' }, { key: 'status', label: '状态', icon: 'fa-gauge-high', hint: '运行指标与最近动态' }, ]; /** 当前标签的元信息(标题行用) */ readonly railCurrent = computed( () => this.railTabs.find((t) => t.key === this.railTab()) ?? this.railTabs[0], ); // ---- 右栏宽度(拖宽 + 本地记忆) ---- private static readonly RAIL_W_KEY = 'fmode_rail_w'; private static readonly RAIL_W_MIN = 280; private static readonly RAIL_W_MAX = 560; private static readonly RAIL_W_DEFAULT = 320; private readonly _railWidth = signal(this.readRailWidth()); readonly railWidth = this._railWidth.asReadonly(); private resizeFrom = 0; private resizeStartX = 0; private readonly onResizeMove = (e: PointerEvent) => { /* 向左拖 = 变宽:宽度增长量是「起点 X - 当前 X」 */ const raw = this.resizeFrom + (this.resizeStartX - e.clientX); /* 预览形态下放宽上限;非预览形态回到 560 */ const next = this.previewFile() ? clampPreviewRailWidth(raw) : clampRailWidth(raw); this._railWidth.set(next); }; private readonly onResizeEnd = () => { document.removeEventListener('pointermove', this.onResizeMove); document.removeEventListener('pointerup', this.onResizeEnd); document.body.classList.remove('is-resizing-rail'); try { localStorage.setItem(DkChatPage.RAIL_W_KEY, String(this._railWidth())); } catch { /* 隐私模式:只保留内存态 */ } }; startResize(e: PointerEvent): void { e.preventDefault(); this.resizeFrom = this._railWidth(); this.resizeStartX = e.clientX; document.addEventListener('pointermove', this.onResizeMove); document.addEventListener('pointerup', this.onResizeEnd); /* 拖动期间禁掉文本选中,否则整页文字会被刷蓝 */ document.body.classList.add('is-resizing-rail'); } resetRailWidth(): void { this._railWidth.set(DkChatPage.RAIL_W_DEFAULT); try { localStorage.setItem(DkChatPage.RAIL_W_KEY, String(DkChatPage.RAIL_W_DEFAULT)); } catch { /* 忽略 */ } } private readRailWidth(): number { try { const v = Number(localStorage.getItem(DkChatPage.RAIL_W_KEY)); if (Number.isFinite(v) && v > 0) return clampRailWidth(v); } catch { /* 忽略 */ } return DkChatPage.RAIL_W_DEFAULT; } /** 左栏:某 agent 的会话列表是否展开(收起时只显示容器行) */ readonly expandedAgents = signal>(new Set()); /** 左栏:哪些容器的「已归档」目录是展开的 */ readonly archivedOpen = signal>(new Set()); /** 待确认移除的会话(null = 无) */ readonly removing = signal(null); /** 当前数字生命的任务(右栏任务面板用) */ readonly agentTasks = computed(() => { const id = this.chat.agentId(); return id ? this.tasks.all().filter((t) => t.agentId === id) : []; }); readonly pct = (v?: number) => fmtPercent(v); readonly tokens = (a: { usage?: { totalTokens?: number } }) => fmtTokens(usageOf(a as never).totalTokens); /** * 「当前任务」文案 —— **唯一实现**在 `TaskPulseService.describe()`。 * 列表行、头部任务条、右栏运行状态**三处共用同一份**,保证左右同步。 */ taskLine(agentId: string): TaskLine { return this.pulse.describe(this.live.agentById(agentId)); } /** 列表行紧凑标签:一次只答一个问题 —— 在不在干活 */ runLabel(agentId: string): string { const line = this.taskLine(agentId); if (line.tone === 'danger') return '异常'; if (line.active) return '执行中'; if (line.tone === 'warning') return '未同步'; return '空闲'; } /** * 列表第二行文案 —— **不与标题行的运行态重复**。 * * 有具体任务时显示任务;否则显示专长(更适合"没在忙"的时候告知用户它是谁)。 */ convSubline(agentId: string, specialty?: string): string { const line = this.taskLine(agentId); // 状态词(空闲/执行中/未同步/异常)已经在标题行,这里不再重复 if (!line.active && (line.tone === 'neutral' || line.tone === 'danger')) { return specialty || '数字生命'; } return line.text || specialty || '数字生命'; } /** 本会话最近动态 */ readonly pulses = computed(() => this.pulse.pulsesFor(this.chat.agentId())); /** * 消息 → 渲染行:**连续的终端活动消息合并成一个折叠组**。 * * 容器把 Hermes 的每一步(`💻 terminal` + 命令、`✍️ Writing ...`) * 都作为独立消息发出来,一条回复能产生十几条 —— 会话被淹没。 * * 规则:相邻且都属于终端活动的消息合成一组;遇到正常对话立即断开。 */ readonly messageRows = computed(() => { const rows: MessageRow[] = []; /* * 🔴 工具组的 key 必须用**组内第一条消息的 id**,不能用 rows.length。 * * 原实现 `tool-${rows.length}-${summary}`:流式追加消息时 rows.length 会变, * 导致同一个工具组在相邻两次渲染里 key 不同 → Angular 销毁重建整个组, * 表现为「内容一下出现、一下消失」(实测复现:气泡数 2→1→2)。 */ let group: { text: string; summary: string; id: string }[] = []; const flush = (): void => { if (group.length === 0) return; const first = group[0]; rows.push({ kind: 'tool', key: `tool-${first.id}`, block: { kind: 'process', steps: group.map((g) => ({ kind: 'tool' as const, label: g.summary, detail: g.text })), }, }); group = []; }; for (const m of this.chat.messages()) { // 空消息(撤回 / 表情回应 / 空 body)不渲染 —— 实测占 7/12 if (!m.text?.trim() && !m.file) continue; if (m.sender === 'agent' && isToolActivityMessage(m.text)) { group.push({ text: m.text!.slice(0, 400), summary: toolActivitySummary(m.text!), id: m.id }); continue; } flush(); rows.push({ kind: 'msg', key: m.id, message: m }); } flush(); return rows; }); /** 某个成果里「还在容器里、未上云盘」的首个附件(没有则 undefined) */ pendingOf(d: Deliverable): { name: string; source: string } | undefined { const a = d.artifacts.find((x) => !x.url && x.source); return a ? { name: a.name, source: a.source! } : undefined; } /** 附件同步失败原因(UI 如实展示,不假装正在同步) */ syncError(deliverableId: string, a: { source: string }): string | undefined { return this.artifactSync.errorOf(deliverableId, a.source); } /** 动态里的时刻(本地毫秒 → HH:MM) */ clock(ms: number): string { return fmtTime(ms); } private readonly messagesEl = viewChild>('messages'); /** 会话列表:仅已接入的数字生命 */ readonly conversations = computed(() => this.live .agents() .filter((a) => a.matrixReady) .map((a) => ({ id: a.id, name: a.name, specialty: a.specialty, currentTask: a.currentTask, unread: a.unread, })) /* * 🔴 **固定顺序**(用户实测反馈:选中项位置会乱跳)。 * 曾按未读数排序 → 未读一变整列重排,用户正在看的会话会跳位。 * 改为按 name 稳定排序(同 name 再按 id),顺序**不随运行期数据变化**。 */ .sort((x, y) => x.name.localeCompare(y.name, 'zh') || x.id.localeCompare(y.id)), ); /** 待预览的消息附件(null = 关闭) */ readonly previewFile = signal<{ url: string; name: string; mimeType: string } | null>(null); /** * 上一次「最后一条消息」的 id。 * * 用于区分「尾部新增」(要滚底)与「头部插入」(分页,保持锚点)。 */ private lastTailId = ''; /** 用户是否主动上翻离开了底部(true 时新消息不强行拉回) */ private userScrolledAway = false; /** 正在加载更早历史:期间禁止任何「贴底」动作,否则锚点会被破坏 */ private loadingEarlier = false; /** * 打开消息附件预览(按类型分发由 app-file-preview 负责)。 * * 🔴 必须同时**打开右栏**:预览已经改成右栏内联, * 若用户之前收起了右栏,只设 previewFile 是看不到任何反应的(实测 bug)。 */ openFile(f: { url: string; name: string; mimeType: string; size?: number }): void { const kind = previewKindOf(f.name || f.url, f.mimeType); /* * 图片 / 音视频不进右栏(用户裁决 2026-10-30): * - 图片 → 深色灯箱,占满视口 * - 音视频 → 居中模态,原生控件自带全屏 * 其余类型 → 右栏内联预览(可切全屏)。 */ if (kind === 'image') { this.lightboxFile.set({ url: f.url, name: f.name, size: f.size ?? 0 }); return; } if (kind === 'video' || kind === 'audio') { this.mediaFile.set({ url: f.url, name: f.name, kind }); return; } this.previewFile.set(f); this.railOpen.set(true); } /* ---- 图片灯箱 / 音视频模态(2026-10-30)---- */ readonly lightboxFile = signal<{ url: string; name: string; size: number } | null>(null); /** 待发送图片点缩略图 → 用同一个灯箱预览(2026-10-31) */ previewPending(pf: { file: File; previewUrl?: string }): void { const url = pf.previewUrl; if (!url) return; this.lightboxFile.set({ url, name: pf.file.name, size: pf.file.size }); } readonly mediaFile = signal<{ url: string; name: string; kind: PreviewKind } | null>(null); mediaKind(m: { kind: PreviewKind }): 'video' | 'audio' { return m.kind === 'video' ? 'video' : 'audio'; } onMediaOpenChange(open: boolean): void { if (!open) this.mediaFile.set(null); } /** * 预览形态下的右栏显示宽度。 * 拖拽时已按预览上限夹取;这里再兜底一次,防止旧记忆值超出。 */ readonly effectiveRailWidth = computed(() => this.previewFile() ? clampPreviewRailWidth(this.railWidth()) : this.railWidth(), ); /** 真实未读数(UnreadService 唯一来源;不用 Agent.unread 的占位值) */ unreadOf(agentId: string): number { return this.unread.countOf(agentId); } /** 可对话状态(判定唯一实现在 models.agentPresence) */ containerState(agentId: string): AgentPresence { return agentPresence(this.live.agentById(agentId)); } /** 当前打开会话的容器状态(用于区分「容器离线」与「自己在连接中」) */ readonly currentContainerState = computed(() => { const id = this.chat.agentId(); return id ? agentPresence(this.live.agentById(id)) : 'offline'; }); readonly filteredConversations = computed(() => { const q = this.keyword().trim().toLowerCase(); if (!q) return this.conversations(); return this.conversations().filter( (c) => c.name.toLowerCase().includes(q) || (c.specialty ?? '').toLowerCase().includes(q), ); }); /** 本会话里的全部文件(按出现顺序,同 url+name 去重) */ readonly sessionFiles = computed(() => { const seen = new Set(); const out: { name: string; url: string; mimeType: string; size: number }[] = []; for (const m of this.chat.messages()) { const f = m.file; if (!f || !f.url) continue; const key = f.url + f.name; if (seen.has(key)) continue; seen.add(key); out.push({ name: f.name, url: f.url, mimeType: f.mimeType, size: f.size }); } return out; }); /** 按 mimeType 选图标(原生附件没有 fileType 字段) */ fileIconByMime(mime: string): string { if (mime.startsWith('image/')) return 'fa-file-image'; if (mime.includes('html')) return 'fa-file-code'; if (mime.includes('pdf')) return 'fa-file-pdf'; if (mime.includes('word') || mime.includes('officedocument.word')) return 'fa-file-word'; if (mime.includes('sheet') || mime.includes('excel')) return 'fa-file-excel'; if (mime.includes('zip')) return 'fa-file-zipper'; return 'fa-file-lines'; } /** 字节数 → 人类可读 */ fmtSize(bytes: number): string { if (!bytes) return ''; if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / 1024 / 1024).toFixed(1)} MB`; } readonly agentDeliverables = computed(() => { const id = this.chat.agentId(); return id ? this.deliverables.byAgent(id) : []; }); constructor() { /* * AC-04.2:新消息到达后滚动到底。 * * 🔴 **只在「尾部新增了消息」时滚底**(用户实测反馈:上翻历史时也被拉到底)。 * 上翻历史走的是 `paginate()` → `messages` 变长但**尾部未变** → * 此处按「最后一条消息 id 是否变化」判定,分页时保持锚点不动。 */ effect(() => { const list = this.chat.messages(); const tailId = list.length ? list[list.length - 1].id : ''; const prev = this.lastTailId; this.lastTailId = tailId; // 首次(prev 为空)或尾部确实变了 → 滚底 if (prev === '' || tailId !== prev) { this.stickToBottom(); } }); /* * 正在输入指示器出现时贴底(2026-11-01:已移入消息流末尾)。 * * 🔴 它现在是消息流的最后一行,出现会让流的高度增加一截。 * 用 rAF + 再等一帧:effect 执行时 DOM 还没插入, * 立即 scrollToBottom 会把「指示器还没占位」的高度当作终点, * 结果它出现在视口下方看不见(截图实测)。 */ effect(() => { if (!this.chat.peerTyping()) return; requestAnimationFrame(() => requestAnimationFrame(() => this.stickToBottom())); }); // 窄窗默认收起右栏(<1150) if (typeof window !== 'undefined' && window.innerWidth < 1150) { this.railOpen.set(false); } // 🔴 监听**路由参数流**而非 snapshot —— 同一组件在 chat/:id 间复用时 // 构造函数不会重跑,只读一次 snapshot 会导致「切换会话无反应」。 this.route.paramMap.subscribe((params) => { void this.onRouteChange(params.get('id'), params.get('sessionId')); }); /* * 成果附件同步:读到成果列表后,把「只有容器路径、没有云盘地址」的附件登记去同步。 * 幂等(服务内部去重),每次列表刷新都可以安全调用。 */ effect(() => { const list = this.deliverables.all(); if (list.length === 0) return; void this.artifactSync.syncPending(list); }); /* * 待建态建出会话后,把 URL 从 /chat/:id/new 换成真实会话地址(2026-11-01)。 * * 🔴 不换的话 URL 一直停在 `new`:刷新页面会重新进入待建态, * 用户看到刚发的会话「不见了」;分享/回退也会回到空白新建页。 * 这里用 replaceUrl,不产生历史记录堆积。 */ effect(() => { const sid = this.chat.sessionId(); const aid = this.chat.agentId(); if (!sid || !aid) return; // 只在当前路由仍是待建态的 `new` 时替换,正常切会话不干预 if (!this.router.url.includes(`/chat/${aid}/new`)) return; void this.router.navigateByUrl( `/${this.device.mode()}/chat/${aid}/${encodeURIComponent(sid)}`, { replaceUrl: true }, ); }); } private async onRouteChange(id: string | null, sessionId: string | null): Promise { this.sessions.load(); await Promise.all([ this.live.ensureLoaded(), this.deliverables.ensureLoaded(), // 右栏任务面板依赖全量任务(按 agentId 过滤) this.tasks.ensureAllLoaded(), ]); if (id) { /* * `sessionId === 'new'` = 「新建对话」的待建地址(不落任何数据)。 * 2026-11-01:新建对话不再预建空会话,而是打开一个空白待建态, * 用户发出第一条消息时才真正创建会话。 */ if (sessionId === 'new') { const ws = this.route.snapshot.queryParamMap.get('ws'); await this.chat.startBlank(id, ws || null); } else { await this.chat.open(id, sessionId ?? undefined); } // 打开后内容不满一屏 → 自动补历史(懒加载的另一半) void this.fillViewportIfNeeded(); } else { const first = this.conversations()[0]; if (first) void this.openConversation(first.id, true); } } openConversation(id: string, replace = false): void { void this.router.navigateByUrl(`/${this.device.mode()}/chat/${id}`, { replaceUrl: replace }); } // ---------- 多会话(左栏两栏式:容器 → 会话) ---------- /** * 左栏分组数据:每个可对话的容器 + 它下面的会话。 * * 排序与 `conversations()` 一致(按名字稳定排序), * **不随消息变动重排** —— 用户正在看的行不会跳位。 * * 搜索规则:匹配容器名 → 显示该容器下全部会话;只匹配会话名 → 只显示命中的会话。 */ readonly groups = computed< { agent: ConversationRow; sessions: ChatSession[]; archived: ChatSession[] }[] >(() => { const map = this.sessions.byAgent(); const kw = this.keyword().trim().toLowerCase(); const out: { agent: ConversationRow; sessions: ChatSession[]; archived: ChatSession[] }[] = []; for (const c of this.filteredConversations()) { /* * 🔴 活跃会话与已归档会话**分开两组渲染**,不是「归档就消失」。 * * 用户要求:归档应当收进**独立目录**,而不是从界面上抹掉 —— * 抹掉会让用户以为对话被删了,也找不回来。 */ let list = (map.get(c.id) ?? []).filter((s) => !s.archived); let archived = (map.get(c.id) ?? []).filter((s) => s.archived); if (kw) { const selfMatch = c.name.toLowerCase().includes(kw) || (c.specialty ?? '').toLowerCase().includes(kw); if (!selfMatch) { list = list.filter((s) => s.title.toLowerCase().includes(kw)); archived = archived.filter((s) => s.title.toLowerCase().includes(kw)); if (list.length === 0 && archived.length === 0) continue; } } out.push({ agent: c, sessions: list, archived }); } return out; }); /** 容器是否展开(当前打开的容器默认展开) */ isExpanded(agentId: string): boolean { return this.expandedAgents().has(agentId) || this.chat.agentId() === agentId; } /** * 展开 / 收起某容器的会话列表。 * * 🔴 **没打开过的容器,首次点击要顺带打开它**。 * 否则:点开 lj-test 只展开了一个空列表(它的会话要「进过这个容器」 * 才会被扫描出来),用户以为这个容器没有对话(实测踩坑)。 * * `openConversation` 会触发 `chat.open()` → 扫描 Matrix 线程 → * 左栏立刻填上该容器已有的对话。用户不需要多点一次。 */ toggleExpand(agentId: string): void { const wasExpanded = this.isExpanded(agentId); const hasSessions = (this.sessions.byAgent().get(agentId) ?? []).length > 0; this.expandedAgents.update((set) => { const next = new Set(set); if (set.has(agentId)) next.delete(agentId); else next.add(agentId); return next; }); // 从未打开过、且左栏没有它的会话 → 点一次就直接进去 if (!wasExpanded && !hasSessions && this.chat.agentId() !== agentId) { this.openConversation(agentId); } } /** 打开指定会话 */ openSession(agentId: string, sessionId: string): void { void this.router.navigateByUrl( `/${this.device.mode()}/chat/${agentId}/${encodeURIComponent(sessionId)}`, ); } /** * 打开容器设置 —— 用**全局模态框**而不是跳整页(2026-10-30 用户反馈)。 * 跳页会丢掉当前会话的滚动位置与上下文,关掉弹层就回到原处。 */ openAgentSettings(agentId: string): void { this.agentModal.open(agentId); } /** * 空会话欢迎区:按小时问候 + 4 条起点建议。 * * 建议只「填入输入框」不直接发送 —— 用户通常要改成自己的口径再发, * 直接发出去反而要撤回。文案取自真实使用场景(交付文件 / 查状态 / 排查 / 同步进度)。 */ readonly suggests: { icon: string; title: string; text: string }[] = [ { icon: 'fa-code', title: '做个单页', text: '把这周的数据整理成一个可以直接打开的 HTML 单页' }, { icon: 'fa-magnifying-glass', title: '看看在忙什么', text: '你现在在做什么?列出正在推进的任务和卡住的地方' }, { icon: 'fa-wrench', title: '排查问题', text: '刚才那次运行失败了,帮我看下日志里是什么原因' }, { icon: 'fa-list-check', title: '同步进度', text: '把今天做完的内容整理成一份进度汇报' }, ]; readonly greeting = computed(() => { const h = new Date().getHours(); if (h < 6) return '凌晨好'; if (h < 12) return '上午好'; if (h < 14) return '中午好'; if (h < 18) return '下午好'; return '晚上好'; }); /** 点建议 → 填入输入框(不直接发送) */ useSuggest(text: string): void { this.chat.setDraft(text); } /** * 会话树发出「新建对话」请求 → 打开选容器模态框(D3)。 * * 工作区归属本轮不做落库:`workspaceId` 只用于模态框里的提示文案, * 真正写入 `ChatSession` 在第 3 轮(见计划文档)。 */ onNewSessionRequest(req: NewSessionRequest): void { this.newSessionWorkspace.set(req.workspaceId); } /** 模态框里可选容器(与左栏 old 列表同源:已接入 Matrix 的数字生命) */ readonly pickableAgents = computed(() => this.conversations()); /** * 工作区名称(模态框提示用)。 * 第 1 轮工作区由会话树组件持有内存态,页面拿不到 —— 先给中性文案, * 第 3 轮工作区下沉到 service 后改读 service。 */ workspaceName(wsId: string): string { if (!wsId) return '日常对话'; return this.workspaceSvc.byId(wsId)?.name ?? '日常对话'; } /** 选中容器 → 在该容器下新建对话(复用原有去重规则) */ createInContainer(agentId: string): void { const targetWs = this.newSessionWorkspace(); this.newSessionWorkspace.set(undefined); this.newSession(agentId, undefined, targetWs ?? null); } /** * 在指定容器下新建对话并立即打开。 * * @param workspaceId 归属工作区(`null` = 日常对话)。只在从模态框选出容器时传入; * 标题栏的「+」不传,沿用日常对话。 */ newSession(agentId: string, event?: Event, workspaceId: string | null = null): void { event?.stopPropagation(); /* * 「新建对话」**不创建任何数据**,只是把界面切到该容器的空白待建态 * (2026-11-01 用户裁决:首次发消息才建会话)。 * * 这样点几次「+」就留几条空壳的问题从根上消失 —— 旧实现要么建空会话、 * 要么得靠 `pruneEmpty` 事后清理,两者都会出错。 * 工作区归属通过 URL 传过去,由聊天页在会话建出来那一刻落地。 */ this.expandedAgents.update((set) => new Set(set).add(agentId)); const qs = workspaceId ? `?ws=${encodeURIComponent(workspaceId)}` : ''; void this.router.navigateByUrl(`/${this.device.mode()}/chat/${agentId}/new${qs}`); } /** 点删除 → 先弹确认(删除类操作必须二次确认) */ confirmRemove(s: ChatSession, event?: Event): void { event?.stopPropagation(); this.removing.set(s); } /** 确认移除(只移除列表索引,Matrix 里的消息不动) */ doRemove(): void { const s = this.removing(); if (!s) return; this.sessions.remove(s.id); this.removing.set(null); /* * 移除的是当前打开的那条 → 回落到该容器的下一条,避免停在空白页。 */ if (this.chat.sessionId() === s.id) { const next = this.sessions.listFor(s.agentId)[0]; if (next) this.openSession(s.agentId, next.id); } } /** 归档 / 取消归档(收进「已归档」目录,不删除、不隐藏) */ toggleArchive(s: ChatSession, event?: Event): void { event?.stopPropagation(); const next = !s.archived; this.sessions.archive(s.id, next); /* * 归档后自动展开该容器的「已归档」目录 —— * 让用户看到对话**去了哪里**,而不是以为它消失了。 */ if (next) { const aid = s.agentId; this.archivedOpen.update((set) => new Set(set).add(aid)); } } /** 展开 / 收起某容器的「已归档」目录 */ toggleArchivedGroup(agentId: string, event?: Event): void { event?.stopPropagation(); this.archivedOpen.update((set) => { const next = new Set(set); if (next.has(agentId)) next.delete(agentId); else next.add(agentId); return next; }); } /** 会话行的时间显示(今天显示时分,更早显示日期) */ sessionTime(ts: number): string { if (!ts) return ''; const d = new Date(ts); const now = new Date(); const sameDay = d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate(); if (sameDay) { return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; } const days = Math.floor((now.getTime() - d.getTime()) / 86400000); if (days === 1) return '昨天'; if (days < 7) return `${days}天`; return `${d.getMonth() + 1}-${d.getDate()}`; } async reload(): Promise { await this.live.refresh(); } /** * 重连 / 重新加载。 * * 🔴 必须走 `force`:`chat.open()` 在「同一 agent + 同一会话 + state=ready」时 * 会短路返回,而断线时 state 仍是 ready —— 不 force 的话按了完全没有反应 * (用户实测:「点击这个重新连接没有任何效果」)。 */ reconnect(): void { const id = this.chat.agentId(); if (id) void this.chat.open(id, this.chat.sessionId() || undefined, true); // Matrix 连接也可能已经断开,顺带重建一次(幂等,已连上时直接返回) void this.matrixSession.kick(); } retryOpen(): void { const id = this.chat.agentId(); if (id) void this.chat.open(id, this.chat.sessionId() || undefined, true); } /** 切换右栏面板:同面板再点则隐藏 */ toggleRail(tab: RailTab): void { if (this.railOpen() && this.railTab() === tab) { this.railOpen.set(false); return; } this.railTab.set(tab); try { localStorage.setItem('fmode_rail_tab', tab); } catch { /* 隐私模式 */ } this.railOpen.set(true); } /** 任务状态中文(右栏用) */ statusText(status: string): string { return TASK_STATUS_TEXT[status as keyof typeof TASK_STATUS_TEXT] ?? status; } /** 消息里的「查看任务」→ 打开右栏任务面板 */ openTaskRail(): void { this.railTab.set('tasks'); this.railOpen.set(true); } goTasks(): void { const id = this.chat.agentId(); if (id) void this.router.navigate(['/', this.device.mode(), 'tasks', id]); } /** * 成果预览(2026-10-31 用户要求):改为**右栏内联**,与消息附件共用同一个预览面板。 * * 原来走全屏遮罩弹窗,和右侧预览是两套观感;现在统一走 `previewFile` 这条链路。 * 产物还没有 url(仍在容器里)时如实提示,不给空白预览。 */ preview(d: Deliverable): void { const url = d.artifacts?.[0]?.url ?? ''; if (!url) { this.previewing.set(d); return; } this.openFile({ url, name: d.filename ?? d.title ?? '成果', mimeType: d.artifacts?.[0]?.type ?? '', }); } fileIcon(type?: string): string { return type === 'CSV' ? 'fa-file-csv' : 'fa-file-lines'; } /** CSV 内容转表格行 */ csvRows(d: Deliverable): string[][] { if (!d.content) return []; return d.content .split(/\r?\n/) .filter((l) => l.trim().length > 0) .map((l) => l.split(',')); } goArtifact(id: string): void { void this.router.navigate(['/', this.device.mode(), 'deliverables'], { queryParams: { focus: id }, }); } goTask(id: string): void { void this.router.navigate(['/', this.device.mode(), 'tasks', id]); } /** * 贴底:**滚动两次**。 * * 🔴 踩坑(2026-10-21 实测):只滚一次时,消息已进 DOM 但 **markdown 还没渲染完**, * 那一刻 `scrollHeight` 偏小,滚完仍差 1700+ px —— 用户打开会话看到的是中间某处, * 而且之后**再也不动**(因为尾部 id 没再变,effect 不再触发)。 * * 做法:立即滚一次(同步可见),下一个宏任务再滚一次(吃掉 md 渲染后的增量)。 * 用 `requestAnimationFrame` 而非 `queueMicrotask`:后者在渲染前执行,量不到最终高度。 */ private stickToBottom(): void { // 用户主动上翻看历史时不要把他拽回来(但首次进入要贴底) if (this.userScrolledAway && this.lastTailId !== '') return; // 正在往前翻页:此时 layout 变化属于「向上插入」,绝不能贴底 if (this.loadingEarlier) return; this.scrollToBottom(); requestAnimationFrame(() => { this.scrollToBottom(); // 图片/mermaid 等异步内容会继续长高,再补一次 setTimeout(() => this.scrollToBottom(), 120); }); } private scrollToBottom(): void { const el = this.messagesEl()?.nativeElement; if (el) el.scrollTop = el.scrollHeight; } /** * AC-04.4:滚动到顶部附近(<80px)自动加载更早历史。 * * 加载前记录 `scrollHeight`,加载后按差值补偿 `scrollTop`, * 使视口**锚定在原来的消息上**(不跳变)。 */ onMessagesScroll(_e: Event): void { const el = this.messagesEl()?.nativeElement; if (!el) return; /* * 记住「用户是否主动离开底部」。 * 距底 > 160px 视为用户在往上翻 —— 此时新消息到达**不要**把他拽回底部 * (否则翻历史翻到一半就被弹走);滚回接近底部时自动恢复贴底。 */ const gap = el.scrollHeight - el.scrollTop - el.clientHeight; this.userScrolledAway = gap > 160; if (el.scrollTop > 80) return; if (this.chat.paginating() || !this.chat.hasMoreHistory()) return; void this.loadEarlier(); } /** * 首屏内容不满一屏时自动补齐(懒加载的另一半)。 * * 🔴 场景:会话首屏固定取 30 条,但短消息一屏能放 40+ 条—— * 用户打开会看到下方大片空白,还以为是「会话就这么多」。 * 这里在渲染后测一次高度,不满就往前补一轮,最多 3 轮, * 避免一次把整个历史拉穿(那反而拖慢首次进入)。 */ private async fillViewportIfNeeded(): Promise { const el = this.messagesEl()?.nativeElement; if (!el) return; for (let i = 0; i < 3; i++) { // 等渲染完成再量(markdown 渲染会撑高内容) await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); const el2 = this.messagesEl()?.nativeElement; if (!el2) return; // 内容已经超出视口 → 不需要补 if (el2.scrollHeight > el2.clientHeight + 8) return; // 没有更早的了 → 补也补不出来 if (!this.chat.hasMoreHistory() || this.chat.paginating()) return; await this.loadEarlier(); } } /** 加载更早历史,并保持滚动锚点 */ /** * 加载更早历史,并**保持滚动锚点**(用户要求:位置不能动)。 * * 🔴 踩坑:原实现用 `queueMicrotask` 补偿 —— 那一刻新消息还没渲染完, * 量到的 `scrollHeight` 仍是旧值,补偿量算成 0 → 视口被顶到上面去了。 * * 正确做法:等**两帧**再量(首帧是布局,次帧含 markdown 渲染后的增量), * 用 `新高度 - 旧高度` 作为补偿量。两次测量都拿实时的 `scrollHeight`。 */ async loadEarlier(): Promise { const el = this.messagesEl()?.nativeElement; if (!el) return; const beforeHeight = el.scrollHeight; const beforeTop = el.scrollTop; this.loadingEarlier = true; const grew = await this.chat.paginate(); if (!grew) { this.loadingEarlier = false; return; } // 两帧之后再量:一帧可能还没完成 markdown 渲染 requestAnimationFrame(() => { requestAnimationFrame(() => { const added = el.scrollHeight - beforeHeight; if (added > 0) el.scrollTop = beforeTop + added; this.loadingEarlier = false; }); }); } }