Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat(chatbot): mark unread replies in the session sidebar like Codex (#131)
Robert0622f6b9207d0a4a
diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsxindex ec80f4af..e04af346 100644--- a/chatbot/src/App.jsx+++ b/chatbot/src/App.jsx@@ -48,7 +48,8 @@ import { isGeneratedArtifact, shouldRevealArtifactPanel } from "./artifact-autorimport { IconButton, Dialog, Menu, SelectMenu, CredentialAction } from "./ui";import { credentialHint, openCredentialSettings } from "./credentials";import { groupSessionHistory, scheduledSession, sessionProjectName } from "./session-history.js";-import { runSessionState, sessionReplyStatus, sessionTooltip } from "./session-status.js";+import { runSessionState, sessionReplyStatus, sessionTooltip, sidebarReplyStatus } from "./session-status.js";+import { unreadReply, useReadReplies } from "./session-unread.js";import MentionPicker from "./MentionPicker";import Participants, { Avatar, authorFor } from "./Participants";import IssueContext from "./IssueContext";@@ -363,6 +364,14 @@ export default function App() {composerPreviews = useRef(new Map());const draftKey = `agentflow.native-chat.draft.${chat.user?.id || "guest"}.${chat.activeId || "new:" + chat.projectId}`;useEffect(() => setMention(null), [draftKey]);+ // The open conversation's reply is reported read; the history list dots+ // the replies the server still counts as unread.+ const readReplies = useReadReplies({+ enabled: realChat.ready,+ sessions: realChat.sessions,+ activeId: realChat.activeId,+ generation: realChat.generation,+ });const conversationRuns = useConversationRuns(chat.session, runsRefresh);// The workspace of this conversation (opened by workbench_workspace_open).// Its git state drives the "改动" view of the side panel.@@ -910,10 +919,13 @@ export default function App() {};}const renderSession = (s, options = {}) => {- const status = sessionReplyStatus(s, s.id === chat.activeId ? {- generation: chat.generation,- busy: chat.busy,- } : undefined);+ const status = sidebarReplyStatus(+ sessionReplyStatus(s, s.id === chat.activeId ? {+ generation: chat.generation,+ busy: chat.busy,+ } : undefined),+ unreadReply(s, { activeId: chat.activeId, read: readReplies }),+ );const runState = runSessionState(s);return (<div@@ -975,9 +987,13 @@ export default function App() {{pinned.includes(s.id) ? (<HarnessIcon name="pin" size={12} className="pin-mark" />) : null}- {status.icon ? (+ {status.icon || status.dot ? (<span className="session-status" data-session-status={status.state} role="img" aria-label={status.label} title={status.label}>- <HarnessIcon name={status.icon} size={15} motion={status.busy ? "busy" : "idle"} />+ {status.icon ? (+ <HarnessIcon name={status.icon} size={15} motion={status.busy ? "busy" : "idle"} />+ ) : (+ <span className="session-unread-dot" aria-hidden="true" />+ )}</span>) : null}</button>diff --git a/chatbot/src/navigation.css b/chatbot/src/navigation.cssindex 20d05598..6ea70d97 100644--- a/chatbot/src/navigation.css+++ b/chatbot/src/navigation.css@@ -233,10 +233,21 @@.chat-shell .session-status[data-session-status="completed"] { color: #29815d; }.chat-shell .session-status[data-session-status="failed"] { color: #ce4444; }.chat-shell .session-status[data-session-status="interrupted"] { color: #b87819; }+.chat-shell .session-status[data-session-status="unread"] { color: #3b82f6; }[data-theme="dark"] .chat-shell .session-status[data-session-status="running"] { color: #9cafff; }[data-theme="dark"] .chat-shell .session-status[data-session-status="completed"] { color: #65bd98; }[data-theme="dark"] .chat-shell .session-status[data-session-status="failed"] { color: #f38989; }[data-theme="dark"] .chat-shell .session-status[data-session-status="interrupted"] { color: #e7b76b; }+[data-theme="dark"] .chat-shell .session-status[data-session-status="unread"] { color: #6ea2ff; }+/* A completed reply the reader has not opened yet (Codex's unread dot). */+.chat-shell .session-unread-dot {+ display: block;+ flex: none;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: currentColor;+}.chat-shell .session-link > .pin-mark {flex: none;margin: 0;diff --git a/chatbot/src/session-status.js b/chatbot/src/session-status.jsindex 174f5edb..8bc2c663 100644--- a/chatbot/src/session-status.js+++ b/chatbot/src/session-status.js@@ -19,6 +19,14 @@ export function sessionReplyStatus(session, { generation, busy = false } = {}) {return states[value === "canceled" ? "cancelled" : value] || states.idle;}+// A completed reply the reader has not opened yet carries a blue dot, as in+// Codex; once read, a completed row is quiet again.+const unreadState = { state: "unread", label: "有新回复未读", dot: true };++export function sidebarReplyStatus(status, unread = false) {+ return unread && status.state === "completed" ? unreadState : status;+}+// Run sessions only earn a chip while something needs the reader: a running// SOP, a run waiting for a person, or a failure. Finished runs stay quiet; the// title already says which SOP they belong to.diff --git a/chatbot/src/session-unread.js b/chatbot/src/session-unread.jsnew file mode 100644index 00000000..2122f937--- /dev/null+++ b/chatbot/src/session-unread.js@@ -0,0 +1,57 @@+import { useEffect, useRef, useState } from "react";+import { sessionPath, write } from "./api.js";++// The history list marks a reply that completed after the reader last opened+// its conversation with a blue dot, as Codex does. The server keeps which+// reply each reader has seen and flags the rest `unread` in the list, so a+// conversation that finished while nobody had the page open is dotted too,+// on every device.+export function unreadReply(session, { activeId = "", read = {} } = {}) {+ if (!session?.unread || !session.generationId || session.id === activeId)+ return false;+ // Read on this page; the next list refresh agrees.+ return read[session.id] !== session.generationId;+}++// The completed reply on screen: the open conversation's live generation, or+// the unread reply its list row names.+function openReply(sessions, activeId, generation) {+ if (!activeId) return "";+ if (+ generation?.id &&+ generation.status === "completed" &&+ (!generation.sessionId || generation.sessionId === activeId)+ )+ return generation.id;+ const row = (sessions || []).find((session) => session.id === activeId);+ return row?.unread && row.generationId ? row.generationId : "";+}++// Reports the open conversation's completed reply as read, once per reply,+// and returns the replies read on this page so their dots clear at once.+export function useReadReplies({+ enabled = true,+ sessions,+ activeId = "",+ generation = null,+}) {+ const [read, setRead] = useState({});+ const reported = useRef(new Set());+ const replyId = enabled ? openReply(sessions, activeId, generation) : "";+ useEffect(() => {+ if (!replyId) return;+ const key = `${activeId}\n${replyId}`;+ if (reported.current.has(key)) return;+ reported.current.add(key);+ setRead((old) =>+ old[activeId] === replyId ? old : { ...old, [activeId]: replyId },+ );+ write(`${sessionPath(activeId)}/read`, { generationId: replyId }).catch(+ () => {+ // Opening the conversation again retries.+ reported.current.delete(key);+ },+ );+ }, [activeId, replyId]);+ return read;+}diff --git a/chatbot/tests/app-render.test.jsx b/chatbot/tests/app-render.test.jsxindex 41bfa9e7..f62cfb20 100644--- a/chatbot/tests/app-render.test.jsx+++ b/chatbot/tests/app-render.test.jsx@@ -669,3 +669,57 @@ describe("sidebar conversation filter", () => {}});});++describe("sidebar reply status", () => {+ test("an unread completed reply shows a blue dot, a running one spins, a failed one warns", async () => {+ const user = userEvent.setup();+ const previous = { ...chat };+ const originalFetch = globalThis.fetch;+ globalThis.fetch = vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ ok: true, recorded: true }) }));+ const now = new Date().toISOString();+ const row = (id, title, generationStatus, generationId, unread = false) => ({+ id, title, projectId: "p1", userId: "u1", generationStatus, generationId, unread, updatedAt: now, messages: [],+ });+ Object.assign(chat, {+ activeId: null,+ session: null,+ projectId: "p1",+ sessions: [+ row("unread", "完成未读", "completed", "g2", true),+ row("read", "完成已读", "completed", "g3"),+ row("busy", "正在生成", "running", "g4"),+ row("broken", "生成出错", "failed", "g5"),+ ],+ });+ const view = render(<App />);+ try {+ const showSidebar = screen.queryByLabelText("显示会话侧边栏");+ if (showSidebar) await user.click(showSidebar);+ const status = (title) =>+ screen.getAllByText(title)[0].closest(".session-link").querySelector(".session-status");+ await waitFor(() => expect(status("完成未读")).toHaveAttribute("data-session-status", "unread"));+ expect(status("完成未读")).toHaveAccessibleName("有新回复未读");+ expect(status("完成未读").querySelector(".session-unread-dot")).not.toBeNull();+ expect(status("完成已读")).toBeNull();+ expect(status("正在生成").querySelector('[data-icon="arc-spinner"]')).not.toBeNull();+ expect(status("生成出错").querySelector('[data-icon="alert"]')).not.toBeNull();++ // Opening the conversation reports the reply read and clears its dot.+ Object.assign(chat, { activeId: "unread" });+ view.rerender(<App />);+ await waitFor(() =>+ expect(globalThis.fetch).toHaveBeenCalledWith(+ "/api/assistant/sessions/unread/read",+ expect.objectContaining({ method: "POST", body: JSON.stringify({ generationId: "g2" }) }),+ ),+ );+ Object.assign(chat, { activeId: null });+ view.rerender(<App />);+ await waitFor(() => expect(status("完成未读")).toBeNull());+ } finally {+ view.unmount();+ globalThis.fetch = originalFetch;+ Object.assign(chat, previous);+ }+ });+});diff --git a/chatbot/tests/session-unread.test.jsx b/chatbot/tests/session-unread.test.jsxnew file mode 100644index 00000000..c99678ff--- /dev/null+++ b/chatbot/tests/session-unread.test.jsx@@ -0,0 +1,100 @@+import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, test, vi } from "vitest";++vi.mock("../src/api.js", async (original) => ({+ ...(await original()),+ write: vi.fn(async () => ({ ok: true, recorded: true })),+}));++import { write } from "../src/api.js";+import { unreadReply, useReadReplies } from "../src/session-unread.js";+import { sessionReplyStatus, sidebarReplyStatus } from "../src/session-status.js";++const row = (id, generationId, extra = {}) => ({+ id,+ generationId,+ generationStatus: "completed",+ unread: true,+ ...extra,+});++describe("unread replies", () => {+ test("a reply the server counts as unread keeps its dot until it is opened", () => {+ const session = row("a", "g2");+ expect(unreadReply(session)).toBe(true);+ expect(unreadReply(session, { activeId: "a" })).toBe(false);+ expect(unreadReply(session, { read: { a: "g2" } })).toBe(false);+ // A newer reply than the one read on this page is unread again.+ expect(unreadReply(session, { read: { a: "g1" } })).toBe(true);+ expect(unreadReply(row("b", "g3", { unread: false }))).toBe(false);+ });++ test("the sidebar swaps a completed reply for a blue dot only while it is unread", () => {+ const completed = sessionReplyStatus({ id: "a", generationStatus: "completed" });+ expect(sidebarReplyStatus(completed, false)).toBe(completed);+ expect(sidebarReplyStatus(completed, true)).toMatchObject({ state: "unread", dot: true });+ expect(completed.icon).toBeUndefined();+ const running = sessionReplyStatus({ id: "a", generationStatus: "running" });+ expect(sidebarReplyStatus(running, true)).toBe(running);+ expect(running).toMatchObject({ icon: "arc-spinner", busy: true });+ const failed = sessionReplyStatus({ id: "a", generationStatus: "failed" });+ expect(sidebarReplyStatus(failed, true)).toBe(failed);+ expect(failed.icon).toBe("alert");+ });+});++describe("useReadReplies", () => {+ beforeEach(() => write.mockClear());++ test("opening a conversation reports its unread reply once and clears the dot", async () => {+ const sessions = [row("a", "g1"), row("b", "g2")];+ const { result, rerender } = renderHook((props) => useReadReplies(props), {+ initialProps: { enabled: true, sessions, activeId: null },+ });+ expect(write).not.toHaveBeenCalled();+ rerender({ enabled: true, sessions, activeId: "b" });+ await waitFor(() => expect(result.current).toEqual({ b: "g2" }));+ expect(write).toHaveBeenCalledWith("/api/assistant/sessions/b/read", { generationId: "g2" });+ rerender({ enabled: true, sessions: [...sessions], activeId: "b" });+ expect(write).toHaveBeenCalledTimes(1);+ expect(unreadReply(sessions[1], { read: result.current })).toBe(false);+ expect(unreadReply(sessions[0], { read: result.current })).toBe(true);+ });++ test("a reply that completes while its conversation is open is read", async () => {+ const sessions = [row("a", "g1", { unread: false })];+ const running = { id: "g2", sessionId: "a", status: "running" };+ const { result, rerender } = renderHook((props) => useReadReplies(props), {+ initialProps: { enabled: true, sessions, activeId: "a", generation: running },+ });+ expect(write).not.toHaveBeenCalled();+ rerender({ enabled: true, sessions, activeId: "a", generation: { ...running, status: "completed" } });+ await waitFor(() => expect(result.current).toEqual({ a: "g2" }));+ expect(write).toHaveBeenCalledWith("/api/assistant/sessions/a/read", { generationId: "g2" });+ });++ test("failed replies, another conversation's reply and a page still loading report nothing", () => {+ const failed = [row("a", "g1", { unread: false, generationStatus: "failed" })];+ renderHook(() =>+ useReadReplies({ sessions: failed, activeId: "a", generation: { id: "g1", sessionId: "a", status: "failed" } }),+ );+ renderHook(() =>+ useReadReplies({ sessions: failed, activeId: "a", generation: { id: "g9", sessionId: "b", status: "completed" } }),+ );+ renderHook(() => useReadReplies({ enabled: false, sessions: [row("a", "g1")], activeId: "a" }));+ expect(write).not.toHaveBeenCalled();+ });++ test("a report that failed is sent again the next time the conversation is opened", async () => {+ write.mockRejectedValueOnce(new Error("offline"));+ const sessions = [row("a", "g1")];+ const { rerender } = renderHook((props) => useReadReplies(props), {+ initialProps: { sessions, activeId: "a" },+ });+ await waitFor(() => expect(write).toHaveBeenCalledTimes(1));+ await Promise.resolve();+ rerender({ sessions, activeId: null });+ rerender({ sessions, activeId: "a" });+ await waitFor(() => expect(write).toHaveBeenCalledTimes(2));+ });+});diff --git a/design.md b/design.mdindex b71d79cd..f832cb0a 100644--- a/design.md+++ b/design.md@@ -253,6 +253,7 @@ Logo 默认 64px,小屏或短屏为 52px;标题为 36px,小屏为 30px。- 首页只保留品牌、输入区和可执行的起始操作,不显示重复面包屑、键盘说明或无意义的上下文提示。- 上传与引用入口合并到 `+` 菜单,输入 `@` 可搜索角色、需求、SOP、运行和仓库;会话主需求仍可关联、更换和解除。- 回复状态以真实 generation 为依据。“回复完成”不等同于项目或任务完成,未知状态不推断成等待审批。+- 会话侧栏行尾的回复状态参照 Codex:回复进行中显示转圈(`arc-spinner`),回复失败或中断显示感叹号(`alert` / `warning`),在用户离开期间完成、尚未打开查看的回复显示 8px 蓝色圆点;打开该会话后圆点消失,已读的完成回复和手动停止的回复不加标记。已读记录由服务端按用户保存每个会话最后看过的回复(`assistant_session_reads`),列表接口据此返回 `unread`:打开会话、或会话打开期间回复完成时,前端调用 `POST /api/assistant/sessions/{id}/read` 记录(`session-unread.js`),换设备也一致。升级前就已结束的回复不算未读,同事发起、自己未参与的项目会话不显示圆点。- 回复进行中发送的消息进入排队托盘(参照 Codex):托盘贴在输入框上方、左右内缩并压在输入框顶边下,不加标题行;每行是排队图标、单行截断的消息和「引导 / 编辑 / 删除」,「引导」打断当前回复立即发送这一条,没有回复在跑时显示为「发送」。停止后托盘顶部提示「已暂停自动发送」并提供继续发送。输入框占位文案不随生成状态变化。- 参与者按实际发过消息的用户统计,浮层在外部点击、焦点离开或 Escape 时关闭。- 未开始的首页不显示产物入口。有会话内容后显示图标入口;有新产物生成时自动展开产物抽屉,让用户不必先点开才能看到产物。没有产物、只恢复历史会话,或窄屏下抽屉会覆盖会话时保持原有收起状态,只显示未读提示,不抢走正在阅读的回复。@@ -434,7 +435,7 @@ Bot 管理页(`#botsView`)按需求列表与运行记录列表的 Harness| `MentionPicker.jsx`、`mention-context.css` | `@` 引用搜索、选择和展开收起 || `ArtifactPanel.jsx`、`useArtifactPanelLayout.js`、`artifact-*.css` | 产物列表、预览和响应式抽屉 || `usePanelPresence.js` | 双向动效的挂载、退出和快速反向控制 |-| `useLocalConversations.js`、`session-status.js` | 本地会话隔离和真实回复状态展示 |+| `useLocalConversations.js`、`session-status.js`、`session-unread.js` | 本地会话隔离、真实回复状态与未读标记展示 || `web/app/hover-ink.*`、`web/app/sliding-tabs.*` | 两套页面共用的悬停和标签页行为 || `web/app/harness-ui.css` | 唯一设计规范:`--hui-*` 令牌、按钮、Status Badge、面板、输入、Selector 与菜单、设置区旧令牌映射和 1200px 外层容器 || `web/app/issues-list.css` | 需求列表页独有的操作列、看板与响应式样式 |diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex d70cf5a7..30b6934c 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -215,9 +215,42 @@ paths:shared: {type: boolean}runId: {type: string}generationStatus: {type: string}+ generationId: {type: string, description: "Latest reply of the conversation"}+ unread: {type: boolean, description: "The latest reply completed after the caller last opened the conversation (sidebar blue dot). Only for conversations the caller takes part in; replies that ended before read tracking existed are never unread."}updatedAt: {type: string, format: date-time}"401":$ref: "#/components/responses/Unauthorized"+ /api/assistant/sessions/{id}/read:+ parameters:+ - name: id+ in: path+ required: true+ schema: {type: string}+ post:+ tags: [Assistant]+ operationId: markAssistantSessionRead+ summary: Record the reply the caller has seen in a conversation+ description: Clears the conversation's unread mark for the caller on every device. Only the conversation's latest reply is recorded; an older generationId changes nothing and returns recorded=false. Stored in MySQL `assistant_session_reads`.+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [generationId]+ properties:+ generationId: {type: string, maxLength: 64}+ responses:+ "200":+ description: "`{ok: true, recorded: boolean}`"+ "400":+ description: Missing or invalid generationId+ "401":+ $ref: "#/components/responses/Unauthorized"+ "403":+ $ref: "#/components/responses/Forbidden"+ "404":+ $ref: "#/components/responses/NotFound"/api/runs/{id}/conversation:parameters:- name: iddiff --git a/internal/domain/assistant.go b/internal/domain/assistant.goindex a3796f13..0756aebd 100644--- a/internal/domain/assistant.go+++ b/internal/domain/assistant.go@@ -109,11 +109,15 @@ type AssistantSession struct {Shared bool `json:"shared,omitempty"`GenerationStatus string `json:"generationStatus,omitempty"`- Archived bool `json:"archived,omitempty"`- ID string `json:"id"`- UserID int64 `json:"userId,omitempty"`- Title string `json:"title"`- TitleEdited bool `json:"titleEdited,omitempty"`+ GenerationID string `json:"generationId,omitempty"`+ // Unread marks, for the listing reader, a reply that completed after they+ // last opened the conversation. Listing only; never stored.+ Unread bool `json:"unread,omitempty"`+ Archived bool `json:"archived,omitempty"`+ ID string `json:"id"`+ UserID int64 `json:"userId,omitempty"`+ Title string `json:"title"`+ TitleEdited bool `json:"titleEdited,omitempty"`// TitleGenerated is set when a background model replaced the first-prompt// title. It is not a user rename: later turns keep it, and a real rename clears it.TitleGenerated bool `json:"titleGenerated,omitempty"`diff --git a/internal/httpapi/assistant_session.go b/internal/httpapi/assistant_session.goindex 0cf599c8..9d1d5f40 100644--- a/internal/httpapi/assistant_session.go+++ b/internal/httpapi/assistant_session.go@@ -3,6 +3,7 @@ package httpapiimport ("crypto/sha256""encoding/hex"+ "errors""io/fs""os""path/filepath"@@ -97,16 +98,23 @@ func (h *assistantHandlers) listSessions(c *gin.Context) {continue}item.GenerationStatus = "idle"+ item.GenerationID = ""+ item.Unread = falseout = append(out, item)}ids := make([]string, 0, len(out))for _, item := range out {ids = append(ids, item.ID)}- statuses := h.repo.AssistantGenerationStatuses(ids)+ statuses := h.repo.AssistantGenerationStatuses(current.ID, ids)for i := range out {- if status, ok := statuses[out[i].ID]; ok {- out[i].GenerationStatus = status+ if state, ok := statuses[out[i].ID]; ok {+ out[i].GenerationStatus = state.Status+ out[i].GenerationID = state.ID+ // A reply that completed while the reader was elsewhere stays+ // unread until they open the conversation (Codex's blue dot).+ out[i].Unread = state.Status == "completed" && state.FinishedAt != nil && !state.Seen &&+ assistantSessionIncludesUser(out[i], current.ID)}}if issueID := c.GetString("assistantIssueID"); issueID != "" {@@ -160,6 +168,59 @@ func (h *assistantHandlers) archiveSession(c *gin.Context) {c.JSON(200, gin.H{"ok": true})}+// markSessionRead records the reply the reader has seen in a conversation, so+// the history list stops marking it unread on every device. An older reply+// is ignored: only the latest one carries a mark.+func (h *assistantHandlers) markSessionRead(c *gin.Context) {+ current, ok := h.requestUser(c.Request, true)+ if !ok {+ c.JSON(401, gin.H{"error": "请先登录后使用 AI 助手"})+ return+ }+ id := strings.TrimSpace(c.Param("id"))+ ownerID, _, _, err := h.conversationReadScope(c, id, current.ID)+ if err != nil {+ c.JSON(403, gin.H{"error": err.Error()})+ return+ }+ var body struct {+ GenerationID string `json:"generationId"`+ }+ if !decode(c, &body) {+ return+ }+ body.GenerationID = strings.TrimSpace(body.GenerationID)+ if body.GenerationID == "" || len(body.GenerationID) > 64 {+ c.JSON(400, gin.H{"error": "请提供回复 ID"})+ return+ }+ recorded, err := h.repo.MarkAssistantSessionRead(current.ID, ownerID, id, body.GenerationID)+ if errors.Is(err, repo.ErrAssistantReplyNotFound) {+ c.JSON(404, gin.H{"error": err.Error()})+ return+ }+ if err != nil {+ c.JSON(500, gin.H{"error": "记录已读失败"})+ return+ }+ c.JSON(200, gin.H{"ok": true, "recorded": recorded})+}++// assistantSessionIncludesUser matches the sidebar's "仅我参与的对话": the+// people a transcript names, or its owner while it names nobody. A+// colleague's conversation the reader never joined is not news to them.+func assistantSessionIncludesUser(item domain.AssistantSession, userID int64) bool {+ if len(item.Participants) == 0 {+ return item.UserID == userID+ }+ for _, participant := range item.Participants {+ if participant.ID == userID {+ return true+ }+ }+ return false+}+func (h *assistantHandlers) session(c *gin.Context) {current, ok := h.requestUser(c.Request, true)if !ok {diff --git a/internal/httpapi/assistant_session_list_test.go b/internal/httpapi/assistant_session_list_test.goindex 3bc82874..1420b73a 100644--- a/internal/httpapi/assistant_session_list_test.go+++ b/internal/httpapi/assistant_session_list_test.go@@ -7,12 +7,14 @@ import ("errors""fmt""os"+ "reflect""strings""testing""time""agentflow/internal/domain""agentflow/internal/repo"+ "github.com/gin-gonic/gin""gorm.io/gorm""gorm.io/gorm/logger")@@ -55,6 +57,7 @@ func putSessionListConversation(t testing.TB, h *assistantHandlers, ownerID int6t.Fatal(err)}t.Cleanup(func() {+ h.repo.DB.Exec("DELETE FROM assistant_session_reads WHERE session_id=?", session.ID)h.repo.DB.Exec("DELETE FROM assistant_generations WHERE session_id=?", session.ID)h.repo.DB.Exec("DELETE FROM assistant_sessions WHERE id=?", session.ID)})@@ -165,9 +168,12 @@ func TestAssistantSessionListPreservesVisibilityAndMetadata(t *testing.T) {if item.ID == branch.ID && (item.RootSessionID != branch.RootSessionID || item.ParentSessionID != branch.ParentSessionID || item.HistoryRevision != 3 || item.ForkMessageIndex != 2) {t.Fatal("shared branch metadata lost")}- if item.ID == job.SessionID && item.GenerationStatus != "running" {+ if item.ID == job.SessionID && (item.GenerationStatus != "running" || item.GenerationID != job.ID) {t.Fatal("generation status lost")}+ if item.ID != job.SessionID && (item.GenerationStatus != "idle" || item.GenerationID != "") {+ t.Fatalf("session without a reply carries generation state: %s", item.ID)+ }}if len(seen) != len(want) {t.Fatalf("missing sessions: got=%v want=%v", seen, want)@@ -176,6 +182,103 @@ func TestAssistantSessionListPreservesVisibilityAndMetadata(t *testing.T) {}}+func TestAssistantSessionListMarksUnreadRepliesUntilOpened(t *testing.T) {+ h, owner, viewer, prefix := sessionListFixture(t)+ project := prefix + "team"+ putSessionListProject(t, h, domain.Project{ID: project, OwnerID: owner.ID, Members: []domain.ProjectMember{{UserID: viewer.ID, Role: "member"}}})+ question := []domain.AssistantMessage{{Role: "user", Content: "question", AuthorID: owner.ID}}+ for _, key := range []string{"done", "legacy", "failed", "busy", "team-chat"} {+ session := domain.AssistantSession{ID: prefix + key, Title: key, Messages: question}+ if key == "team-chat" {+ session.ProjectID = project+ }+ putSessionListConversation(t, h, owner.ID, session)+ }+ reply := func(key, id, status string) {+ t.Helper()+ g := domain.AssistantGeneration{ID: prefix + id, SessionID: prefix + key, UserID: owner.ID, Status: "running"}+ if err := h.repo.BeginAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ if status != "running" {+ g.Status = status+ if err := h.repo.CheckpointAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ }+ }+ reply("done", "g1", "completed")+ reply("legacy", "g-legacy", "completed")+ // A reply that ended before finish times were recorded stays unmarked.+ if err := h.repo.DB.Exec("UPDATE assistant_generations SET finished_at = NULL WHERE session_id = ?", prefix+"legacy").Error; err != nil {+ t.Fatal(err)+ }+ reply("failed", "g-failed", "failed")+ reply("busy", "g-busy", "running")+ reply("team-chat", "g-team", "completed")++ unread := func(user domain.User) map[string]bool {+ t.Helper()+ c, rec := workbenchContext(user, "GET", "/api/assistant/sessions", bytes.NewBuffer(nil))+ h.listSessions(c)+ if rec.Code != 200 {+ t.Fatalf("list status %d: %s", rec.Code, rec.Body)+ }+ var list []domain.AssistantSession+ if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil {+ t.Fatal(err)+ }+ out := map[string]bool{}+ for _, item := range list {+ if strings.HasPrefix(item.ID, prefix) {+ out[strings.TrimPrefix(item.ID, prefix)] = item.Unread+ }+ }+ return out+ }+ markRead := func(user domain.User, key, generationID string) int {+ t.Helper()+ body := bytes.NewBufferString(`{"generationId":"` + generationID + `"}`)+ c, rec := workbenchContext(user, "POST", "/api/assistant/sessions/"+prefix+key+"/read", body)+ c.Params = gin.Params{{Key: "id", Value: prefix + key}}+ h.markSessionRead(c)+ return rec.Code+ }++ if got := unread(owner); !reflect.DeepEqual(got, map[string]bool{"done": true, "legacy": false, "failed": false, "busy": false, "team-chat": true}) {+ t.Fatalf("owner unread marks: %v", got)+ }+ // The viewer can see the colleague's project chat but never joined it.+ if got := unread(viewer); !reflect.DeepEqual(got, map[string]bool{"team-chat": false}) {+ t.Fatalf("viewer unread marks: %v", got)+ }+ if code := markRead(viewer, "done", prefix+"g1"); code != 404 {+ t.Fatalf("another user's private conversation was marked read: %d", code)+ }+ var stray int64+ h.repo.DB.Table("assistant_session_reads").Where("user_id = ? AND session_id = ?", viewer.ID, prefix+"done").Count(&stray)+ if stray != 0 {+ t.Fatal("a reader recorded a conversation they cannot open")+ }+ if code := markRead(owner, "done", prefix+"g0"); code != 200 || !unread(owner)["done"] {+ t.Fatalf("an older reply cleared the mark: %d", code)+ }+ if code := markRead(owner, "done", prefix+"g1"); code != 200 || unread(owner)["done"] {+ t.Fatalf("opening the conversation did not clear the mark: %d", code)+ }+ reply("done", "g2", "running")+ if unread(owner)["done"] {+ t.Fatal("a running reply is unread")+ }+ next := domain.AssistantGeneration{ID: prefix + "g2", SessionID: prefix + "done", UserID: owner.ID, Status: "completed"}+ if err := h.repo.CheckpointAssistantGeneration(next); err != nil {+ t.Fatal(err)+ }+ if !unread(owner)["done"] {+ t.Fatal("the next completed reply is not unread")+ }+}+type sessionListQueryLog struct {logger.Interfacequeries []stringdiff --git a/internal/httpapi/server.go b/internal/httpapi/server.goindex 16a499b9..dfb2d882 100644--- a/internal/httpapi/server.go+++ b/internal/httpapi/server.go@@ -308,6 +308,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Servg.PUT("/api/assistant/sessions/:id/issue", asst.sessionIssue)g.GET("/api/assistant/sessions", asst.listSessions)g.POST("/api/assistant/sessions/:id/archive", asst.archiveSession)+ g.POST("/api/assistant/sessions/:id/read", asst.markSessionRead)g.POST("/api/assistant/sessions/:id/fork", asst.forkSession)g.GET("/api/assistant/sessions/:id", asst.session)g.PUT("/api/assistant/sessions/:id/sandbox", asst.sessionSandbox)diff --git a/internal/repo/assistant.go b/internal/repo/assistant.goindex 6f0a1414..4ddfc28c 100644--- a/internal/repo/assistant.go+++ b/internal/repo/assistant.go@@ -349,6 +349,9 @@ func (r *AssistantRepo) putAssistantSession(userID int64, v domain.AssistantSess}}v.UserID = userID+ // The latest reply and its read state are projections for the history+ // list, recomputed on every listing; a saved transcript never stores them.+ v.GenerationID, v.Unread = "", falsederiveAssistantParticipants(&v, v.Messages)return upsert(r.DB, "assistant_sessions", map[string]any{"id": v.ID,@@ -419,6 +422,9 @@ func (r *AssistantRepo) DeleteAssistantSession(userID int64, id string) error {if res.RowsAffected == 0 {return fmt.Errorf("assistant session not found")}+ if err := tx.Where("session_id = ?", id).Delete(&assistantSessionReadRow{}).Error; err != nil {+ return err+ }return tx.Where("session_id = ? AND user_id = ?", id, userID).Delete(&assistantGenerationRow{}).Error})}diff --git a/internal/repo/assistant_generations.go b/internal/repo/assistant_generations.goindex d2f386ed..2b364c9a 100644--- a/internal/repo/assistant_generations.go+++ b/internal/repo/assistant_generations.go@@ -19,6 +19,10 @@ type assistantGenerationRow struct {CancelRequested boolPayload []byte `gorm:"type:json"`UpdatedAt time.Time+ // FinishedAt is set when a turn ends through a checkpoint and cleared when+ // the next turn starts. Rows that ended before the column existed keep+ // NULL, which is how read tracking leaves older history unmarked.+ FinishedAt *time.Time}func (assistantGenerationRow) TableName() string { return "assistant_generations" }@@ -91,7 +95,7 @@ func (r *AssistantRepo) BeginAssistantGeneration(g domain.AssistantGeneration, pif old.Status == "running" {return fmt.Errorf("此会话正在生成,请等待完成或停止")}- return tx.Model(&old).Updates(map[string]any{"generation_id": g.ID, "status": "running", "cancel_requested": false, "payload": mustJSON(g), "updated_at": time.Now().UTC()}).Error+ return tx.Model(&old).Updates(map[string]any{"generation_id": g.ID, "status": "running", "cancel_requested": false, "payload": mustJSON(g), "updated_at": time.Now().UTC(), "finished_at": nil}).Error}if !errors.Is(err, gorm.ErrRecordNotFound) {return err@@ -111,7 +115,12 @@ func (r *AssistantRepo) CheckpointAssistantGeneration(g domain.AssistantGeneratiif g.Steer == nil && current.Steer != nil {g.Steer = current.Steer}- res := tx.Model(&row).Updates(map[string]any{"status": g.Status, "payload": mustJSON(g), "updated_at": time.Now().UTC()})+ now := time.Now().UTC()+ changes := map[string]any{"status": g.Status, "payload": mustJSON(g), "updated_at": now}+ if g.Status != "running" {+ changes["finished_at"] = now+ }+ res := tx.Model(&row).Updates(changes)if res.Error != nil {return res.Error}@@ -145,13 +154,40 @@ func (r *AssistantRepo) CancelAssistantGeneration(userID int64, sessionID, id streturn nil}-func (r *AssistantRepo) AssistantGenerationStatuses(ids []string) map[string]string {- out := map[string]string{}+// AssistantGenerationState is the latest reply of a conversation as the+// history list shows it to one reader.+type AssistantGenerationState struct {+ ID string+ Status string+ // FinishedAt is when the reply ended. Replies that ended before it was+ // recorded have none, so read tracking leaves older history unmarked.+ FinishedAt *time.Time+ // Seen reports that the reader has opened the conversation since this+ // reply (see MarkAssistantSessionRead).+ Seen bool+}++// AssistantGenerationStatuses reads the latest reply of each conversation+// and whether the reader has seen it, in one query for the whole list.+func (r *AssistantRepo) AssistantGenerationStatuses(readerID int64, ids []string) map[string]AssistantGenerationState {+ out := map[string]AssistantGenerationState{}if len(ids) == 0 {return out}- var rows []assistantGenerationRow- if r.DB.Select("session_id,status,updated_at").Where("session_id IN ?", ids).Find(&rows).Error != nil {+ var rows []struct {+ SessionID string+ GenerationID string+ Status string+ UpdatedAt time.Time+ FinishedAt *time.Time+ ReadID *string+ }+ err := r.DB.Table("assistant_generations AS g").+ Select("g.session_id, g.generation_id, g.status, g.updated_at, g.finished_at, r.generation_id AS read_id").+ Joins("LEFT JOIN assistant_session_reads AS r ON r.session_id = g.session_id AND r.user_id = ?", readerID).+ Where("g.session_id IN ?", ids).+ Scan(&rows).Error+ if err != nil {return out}for _, row := range rows {@@ -159,7 +195,12 @@ func (r *AssistantRepo) AssistantGenerationStatuses(ids []string) map[string]strif status == "running" && time.Since(row.UpdatedAt) > 45*time.Second {status = "interrupted"}- out[row.SessionID] = status+ out[row.SessionID] = AssistantGenerationState{+ ID: row.GenerationID,+ Status: status,+ FinishedAt: row.FinishedAt,+ Seen: row.ReadID != nil && *row.ReadID == row.GenerationID,+ }}return out}diff --git a/internal/repo/assistant_session_reads.go b/internal/repo/assistant_session_reads.gonew file mode 100644index 00000000..45cf2491--- /dev/null+++ b/internal/repo/assistant_session_reads.go@@ -0,0 +1,55 @@+package repo++import (+ "errors"+ "strings"+ "time"++ "gorm.io/gorm"+ "gorm.io/gorm/clause"+)++// ErrAssistantReplyNotFound: the conversation, as its owner holds it, has no+// reply to mark read.+var ErrAssistantReplyNotFound = errors.New("对话不存在或还没有回复")++// assistantSessionReadRow is the latest reply a reader has seen in a+// conversation. The history list marks a reply that completed after it as+// unread until the reader opens the conversation, on any device.+type assistantSessionReadRow struct {+ UserID int64 `gorm:"column:user_id;primaryKey;autoIncrement:false"`+ SessionID string `gorm:"column:session_id;primaryKey;size:64;index:idx_assistant_session_reads_session"`+ GenerationID string `gorm:"column:generation_id;size:64"`+ Updated time.Time `gorm:"column:updated_at"`+}++func (assistantSessionReadRow) TableName() string { return "assistant_session_reads" }++// MarkAssistantSessionRead records that the reader has seen the reply of a+// conversation owned by ownerID. Only the latest reply is recorded, so a+// stale tab reporting an older one cannot bring back a mark another tab+// cleared; it reports false and changes nothing.+func (r *AssistantRepo) MarkAssistantSessionRead(readerID, ownerID int64, sessionID, generationID string) (bool, error) {+ sessionID = assistantRecordID(sessionID)+ generationID = strings.TrimSpace(generationID)+ if readerID <= 0 || ownerID <= 0 || sessionID == "" || generationID == "" {+ return false, ErrAssistantReplyNotFound+ }+ var latest assistantGenerationRow+ err := r.DB.Select("generation_id").Where("session_id = ? AND user_id = ?", sessionID, ownerID).Take(&latest).Error+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return false, ErrAssistantReplyNotFound+ }+ if err != nil {+ return false, err+ }+ if latest.GenerationID != generationID {+ return false, nil+ }+ row := assistantSessionReadRow{UserID: readerID, SessionID: sessionID, GenerationID: generationID, Updated: time.Now().UTC()}+ err = r.DB.Clauses(clause.OnConflict{+ Columns: []clause.Column{{Name: "user_id"}, {Name: "session_id"}},+ DoUpdates: clause.AssignmentColumns([]string{"generation_id", "updated_at"}),+ }).Create(&row).Error+ return err == nil, err+}diff --git a/internal/repo/assistant_session_reads_test.go b/internal/repo/assistant_session_reads_test.gonew file mode 100644index 00000000..5c82d871--- /dev/null+++ b/internal/repo/assistant_session_reads_test.go@@ -0,0 +1,82 @@+package repo++import (+ "errors"+ "testing"++ "agentflow/internal/domain"+)++func TestAssistantSessionReadsFollowTheLatestReply(t *testing.T) {+ s, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ defer s.Close()+ if err := s.PutAssistantSession(11, domain.AssistantSession{ID: "chat", Title: "chat"}); err != nil {+ t.Fatal(err)+ }+ state := func(reader int64) AssistantGenerationState {+ t.Helper()+ return s.AssistantGenerationStatuses(reader, []string{"chat"})["chat"]+ }+ finish := func(g domain.AssistantGeneration) {+ t.Helper()+ if err := s.BeginAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ if got := state(11); got.ID != g.ID || got.Status != "running" || got.FinishedAt != nil || got.Seen {+ t.Fatalf("a running reply is finished or seen: %+v", got)+ }+ g.Status = "completed"+ if err := s.CheckpointAssistantGeneration(g); err != nil {+ t.Fatal(err)+ }+ if got := state(11); got.Status != "completed" || got.FinishedAt == nil || got.Seen {+ t.Fatalf("a finished reply lost its finish time or is seen: %+v", got)+ }+ }++ finish(domain.AssistantGeneration{ID: "one", SessionID: "chat", UserID: 11, Status: "running"})+ if ok, err := s.MarkAssistantSessionRead(11, 11, "chat", "other"); ok || err != nil {+ t.Fatalf("a reply that is not the latest was recorded: %v %v", ok, err)+ }+ // A reader resolves conversations in the owner's namespace only.+ if ok, err := s.MarkAssistantSessionRead(12, 12, "chat", "one"); ok || !errors.Is(err, ErrAssistantReplyNotFound) {+ t.Fatalf("another user's reply was found in the reader's namespace: %v %v", ok, err)+ }+ if ok, err := s.MarkAssistantSessionRead(11, 11, "chat", "one"); !ok || err != nil {+ t.Fatalf("latest reply not recorded: %v %v", ok, err)+ }+ if !state(11).Seen || state(12).Seen {+ t.Fatal("read state is not per reader")+ }++ // The next reply starts unread again, and a stale tab cannot clear it.+ finish(domain.AssistantGeneration{ID: "two", SessionID: "chat", UserID: 11, Status: "running"})+ if ok, _ := s.MarkAssistantSessionRead(11, 11, "chat", "one"); ok || state(11).Seen {+ t.Fatal("an older reply cleared the newer one")+ }+ if ok, _ := s.MarkAssistantSessionRead(11, 11, "chat", "two"); !ok || !state(11).Seen {+ t.Fatal("newer reply not recorded")+ }+ if ok, err := s.MarkAssistantSessionRead(11, 11, "missing", "two"); ok || !errors.Is(err, ErrAssistantReplyNotFound) {+ t.Fatalf("a conversation without replies was recorded: %v %v", ok, err)+ }++ // Rows that ended before finish times were recorded stay unmarked.+ if err := s.DB.Exec("UPDATE assistant_generations SET finished_at = NULL WHERE session_id = ?", "chat").Error; err != nil {+ t.Fatal(err)+ }+ if state(12).FinishedAt != nil {+ t.Fatal("legacy reply reports a finish time")+ }++ if err := s.DeleteAssistantSession(11, "chat"); err != nil {+ t.Fatal(err)+ }+ var left int64+ if err := s.DB.Table("assistant_session_reads").Where("session_id = ?", "chat").Count(&left).Error; err != nil || left != 0 {+ t.Fatalf("deleted conversation kept read records: %d %v", left, err)+ }+}diff --git a/internal/repo/models.go b/internal/repo/models.goindex 78ec9aff..6a90c116 100644--- a/internal/repo/models.go+++ b/internal/repo/models.go@@ -687,7 +687,7 @@ func allModels() []any {runPreviewRow{}, previewSessionRow{}, previewBlobRow{}, WorkspaceCheckpoint{}, workspaceCheckpointChunk{},mrDeliveryStateRow{}, definitionRevisionRow{},runnerRow{}, runnerTaskRow{}, runnerTaskEventRow{}, userRunnerPrefRow{},- assistantSessionRow{}, assistantTaskRow{}, assistantGenerationRow{},+ assistantSessionRow{}, assistantTaskRow{}, assistantGenerationRow{}, assistantSessionReadRow{},chatRoomRow{}, chatMessageRow{},requirementSpaceRow{}, spaceMemberRow{}, spaceArtifactRow{}, spaceArtifactRevisionRow{}, spaceThreadRow{},engineInstanceRow{},diff --git a/migrations/026_assistant_session_reads.sql b/migrations/026_assistant_session_reads.sqlnew file mode 100644index 00000000..a59f94bd--- /dev/null+++ b/migrations/026_assistant_session_reads.sql@@ -0,0 +1,21 @@+-- Optional manual additive DDL. Startup AutoMigrate also adds this column and+-- table. No backfill: replies that ended before finished_at existed keep NULL+-- and are never marked unread, so upgrading does not light up old history.+SET @asst_finished_at_ddl = IF(+ (SELECT COUNT(*) FROM information_schema.columns+ WHERE table_schema=DATABASE() AND table_name='assistant_generations' AND column_name='finished_at')=0,+ 'ALTER TABLE assistant_generations ADD COLUMN finished_at DATETIME(3) NULL',+ 'SELECT 1');+PREPARE asst_finished_at_stmt FROM @asst_finished_at_ddl;+EXECUTE asst_finished_at_stmt;+DEALLOCATE PREPARE asst_finished_at_stmt;++-- The latest reply each reader has seen per conversation (sidebar unread dot).+CREATE TABLE IF NOT EXISTS assistant_session_reads (+ user_id BIGINT NOT NULL,+ session_id VARCHAR(64) NOT NULL,+ generation_id VARCHAR(64),+ updated_at DATETIME(3),+ PRIMARY KEY (user_id, session_id),+ INDEX idx_assistant_session_reads_session (session_id)+) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;