chat

package
v2.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package chat 是聊天消息接口的核心(设计稿 03 / 旧稿 rev 5)。

1:1 会话「隐式存在」:id = wf:<workflow_id>,消息由四个旧来源(汇报与回复、你追加的话、提问卡与答复、任务进展) 读时合成一条按发送时间排序的流,旧表一行不动;已读游标与系统事件落在两张新表里。 群会话(阶段 2b)有原生的 chat_messages,由同一个接口对外,用 grp: 前缀区分。

这个包只放「合成、排序、分页、状态推导」这些纯逻辑,取数在 internal/store(chat_stream.go)。

Index

Constants

View Source
const (
	// DefaultLimit / MaxLimit 是一页消息的条数。
	DefaultLimit = 50
	MaxLimit     = 200
)
View Source
const (
	KindText       = "text"       // 文字消息(Agent 的汇报正文、你的回复与追加)
	KindProgress   = "progress"   // 进展:Agent 的进度气泡与任务进展卡(连续出现时界面叠放)
	KindAsk        = "ask"        // 提问卡(含授权卡:task_seq > 0)
	KindPlan       = "plan"       // 计划确认卡
	KindBlock      = "block"      // 阻塞确认卡:Agent 正停在这一轮等你
	KindDecision   = "decision"   // 文档决策卡(按文档汇总)
	KindAlert      = "alert"      // 守护告警卡(预留)
	KindSystem     = "system"     // 系统行:居中的灰色小字
	KindCheckpoint = "checkpoint" // 检查点胶囊(预留)
)

消息种类。

View Source
const (
	SenderHuman  = "human"
	SenderAgent  = "agent"
	SenderSystem = "system"
)

发送者种类。

View Source
const (
	StatusSent      = "sent"      // Hub 收下了
	StatusDelivered = "delivered" // Agent 已被提醒(hook 提醒或回执提示行带到了它面前),但还没读全文
	StatusRead      = "read"      // 读到了全文(你发的:Agent 取走;Agent 发的:你的已读游标越过了它)
	StatusHandled   = "handled"   // Agent 确认处理了
	StatusRetracted = "retracted" // 读到之后被撤回
	StatusExpired   = "expired"   // 保留期内一直没被读到
	StatusAnswered  = "answered"  // 你的答复(投递状态未知的旧数据)
)

消息状态。你发的消息:sent → delivered → read → handled,旁支 retracted / expired; Agent 发的消息:sent → read(你读到了);卡片沿用确认项的状态(pending / answered / dismissed / withdrawn / expired)。

View Source
const (
	SourceFeedbackSession = "feedback_session"
	SourceQueuedFeedback  = "queued_feedback"
	SourceConfirmItem     = "confirm_item"
	SourceWorkItemUpdate  = "work_item_update"
	SourceEvent           = "event"
)

消息来源(调试与对拍用,前端不依赖)。

View Source
const (
	PrefixReport   = "s" // s:sess-ab12cd34  Agent 的汇报(或进度气泡)
	PrefixReply    = "r" // r:sess-ab12cd34  你对这一轮的回复
	PrefixEnding   = "x" // x:sess-ab12cd34  这一轮等待超时 / 被取消(系统行)
	PrefixInbox    = "q" // q:12             你追加的话
	PrefixRevoke   = "v" // v:12             你撤回了一条追加(系统行)
	PrefixCard     = "c" // c:Q12            Agent 的提问 / 计划卡
	PrefixAnswer   = "a" // a:Q12            你对卡的答复
	PrefixDecision = "d" // d:7              一篇文档的决策汇总卡
	PrefixUpdate   = "u" // u:345            任务进展
	PrefixEvent    = "e" // e:77             系统事件
)

消息 id 的来源前缀:旧表主键不变,id 就不变,引用与书签都稳。

View Source
const DirectPrefix = "wf:"

DirectPrefix 是 1:1 会话 id 的前缀。

View Source
const GroupPrefix = "grp:"

GroupPrefix 是群会话 id 的前缀(阶段 2b)。

View Source
const HumanName = "你"

HumanName 是你在聊天里的显示名。

Variables

View Source
var ErrBadCursor = errors.New("游标无效")

ErrBadCursor 表示游标不是本服务生成的(被截断、被篡改或来自别的会话类型)。

Functions

func AgentReader

func AgentReader(workflowID string) string

AgentReader 是 Agent 一方在已读游标表里的 reader_ref。

func AnswerTime

func AnswerTime(it model.ConfirmItem) time.Time

AnswerTime 是你对卡的答复的时间:作答时间;放弃的卡没有作答时间,取最后更新时间。

func DescribeGroupError

func DescribeGroupError(err error) string

DescribeGroupError 把群聊规则错误翻成一句给 Agent / 界面看的话。

func DirectID

func DirectID(workflowID string) string

DirectID 返回一个工作流的 1:1 会话 id。

func InboxStatus

func InboxStatus(q model.QueuedFeedback) (string, *time.Time)

InboxStatus 由追加行(State 已由 store 推导)给出你发的消息的状态与进入该状态的时间。 已送达只有「被提醒过但还没读全文」才成立:hook 提醒过,或回执里的 inbox: 提示行带到过它面前。

func IsGroupID

func IsGroupID(id string) bool

IsGroupID 报告会话 id 是不是群。

func ParseDirectID

func ParseDirectID(conversationID string) (workflowID string, ok bool)

ParseDirectID 解析 1:1 会话 id;不是 wf:<非空> 时 ok 为 false。

func Preview

func Preview(m Message, n int) string

Preview 取一条消息的一行预览(会话列表、通知、chat list 用):优先正文,其次标题。

func ReplyHash

func ReplyHash(ref string) (string, bool)

ReplyHash 把 reply_to 引用(s:<session_id>)换成 8 位短哈希。

func ReplyTime

func ReplyTime(s model.FeedbackSession) time.Time

ReplyTime 是你的回复的时间:优先 responded_at,旧数据依次回退到 consumed_at、updated_at。

func TieOrder

func TieOrder() []string

TieOrder 按「同一毫秒内的先后」列出来源名,用于与前端 timeline.ts 的 KIND_RANK 对拍(见 testdata/tie_order.json)。

Types

type AgentGroupDigest

type AgentGroupDigest struct {
	GroupID   string
	Title     string
	Unread    int
	Mentioned int
}

AgentGroupDigest 是某个工作流在一个群里的未读情况(chat list 与回执尾行用)。

type AgentRead

type AgentRead struct {
	Items []Message
	More  bool
	Group *GroupInfo
	// MaxSeq 是返回的最大序号(已读游标据此推进)。
	MaxSeq int64
}

AgentRead 是 Agent 的 chat read 在群里的结果。

type Anchor

type Anchor struct {
	Commit  string `json:"commit"`
	Subject string `json:"subject,omitempty"`
}

Anchor 是 Agent 申报的交付锚点(仓库最新提交)。

type Attachment

type Attachment struct {
	Type   string `json:"type"` // 目前只有 image
	URL    string `json:"url"`
	Name   string `json:"name,omitempty"`
	Width  int    `json:"width,omitempty"`
	Height int    `json:"height,omitempty"`
}

Attachment 是消息里的图片:url 是带内容哈希的直链(不含令牌),Base64 一律不进消息流。

type Builder

type Builder struct {
	ConversationID string
	WorkflowID     string
	// Agent 是 Agent 消息的发送者(取这个工作流当前身份的显示名)。
	Agent Sender
	// ReadMs 是你的已读游标(Unix 毫秒):Agent 的消息发送时间不晚于它就算已读。
	ReadMs int64
}

Builder 把旧来源的行合成成消息。它不碰数据库,输入输出都是内存里的值,方便表驱动测试。

func NewBuilder

func NewBuilder(workflowID, agentName string, readMs int64) Builder

NewBuilder 为一个工作流的 1:1 会话建合成器。agentName 为空时回落到「Agent」。

func (Builder) Answer

Answer 是你对提问卡 / 计划卡的答复。delivery 是它对应的收件箱投递行(旧数据没有,传 nil): 有就用它的四态,没有只能说「已答复」。

func (Builder) Card

Card 是 Agent 的提问卡 / 计划确认卡(带任务关联的提问卡就是授权卡,界面按 card.task_seq 判断)。

func (Builder) Decision

func (b Builder) Decision(g DecisionGroup, first time.Time) Message

Decision 是一篇文档里的决策汇总卡;时间取该文档最早一项的创建时间。

func (Builder) Ending

func (b Builder) Ending(s model.FeedbackSession) Message

Ending 是「这一轮等待超时 / 被取消」的系统行。

func (Builder) Event

func (b Builder) Event(ev model.ConversationEvent) Message

Event 是会话时间线上的系统事件。

func (Builder) InboxItem

func (b Builder) InboxItem(q model.QueuedFeedback) Message

InboxItem 是你随时追加的话。

func (Builder) Notice

func (b Builder) Notice(s model.FeedbackSession) Message

Notice 是 Agent 不阻塞地发布的进度气泡。

func (Builder) Reply

func (b Builder) Reply(s model.FeedbackSession) Message

Reply 是你对某一轮汇报的回复(含「秒回」带走的追加)。user_messages 是回复里的快捷短语,放进 meta.chips。

func (Builder) ReplyAfterMerge

func (b Builder) ReplyAfterMerge(s model.FeedbackSession, merged []model.QueuedFeedback) (Message, bool)

ReplyAfterMerge 是 Reply 的变体:这一轮的回复里有一部分是「秒回」时并进来的追加(merged,按被取走的顺序), 它们在聊天里已经各是一条独立的消息,这里只留合并之外的部分(秒回之后你又补的话 / 图片 / 快捷短语)。 剩下的是空的就返回 false(这一轮没有单独的回复)。回复正文对不上合并的写法时(例如被改过)原样保留,宁可重复也不丢内容。

func (Builder) Report

func (b Builder) Report(s model.FeedbackSession) Message

Report 是 Agent 的一轮汇报。Agent 正停在这一轮等你(pending)时是「阻塞确认卡」。

func (Builder) Retraction

func (b Builder) Retraction(q model.QueuedFeedback) Message

Retraction 是「你撤回了一条消息」的系统行(不带正文),时间是撤回的时刻。

func (Builder) TaskUpdate

func (b Builder) TaskUpdate(u store.WorkflowUpdate) Message

TaskUpdate 是 Agent 写下的一条任务进展。

type DecisionGroup

type DecisionGroup struct {
	DocID   uint                    `json:"doc_id"`
	DocPath string                  `json:"doc_path,omitempty"`
	Title   string                  `json:"title,omitempty"`
	Pending int                     `json:"pending"`
	Items   []model.ConfirmItemView `json:"items"`
}

DecisionGroup 是一篇文档里的全部决策项(按文档汇总成一张卡)。

type Delivery

type Delivery struct {
	Ref    string `json:"ref"`
	Name   string `json:"name"`
	Status string `json:"status"`
}

Delivery 是被点名的成员各自的投递状态(已送达 / 已读 / 已处理)。

type GroupInfo

type GroupInfo struct {
	ID           string        `json:"id"`
	Title        string        `json:"title"`
	ProjectID    string        `json:"project_id,omitempty"`
	CreatedAt    time.Time     `json:"created_at"`
	Archived     bool          `json:"archived"`
	Members      []GroupMember `json:"members"`
	CrossProject bool          `json:"cross_project"`
	Projects     []string      `json:"projects,omitempty"`
}

GroupInfo 是群的基本信息与成员。

type GroupMember

type GroupMember struct {
	Kind       string     `json:"kind"` // human | workflow
	Ref        string     `json:"ref"`  // user | 工作流编号
	Name       string     `json:"name"`
	Role       string     `json:"role"`
	WorkflowID string     `json:"workflow_id,omitempty"`
	PushPolicy string     `json:"push_policy"`
	MutedUntil *time.Time `json:"muted_until,omitempty"`
	JoinedAt   time.Time  `json:"joined_at"`
	Left       bool       `json:"left,omitempty"`
	// 下面几项只有 Agent 成员有:来自 Agent 状态机的展示状态。
	State      string `json:"state,omitempty"`
	Sub        string `json:"sub,omitempty"`
	WaitingYou bool   `json:"waiting_you,omitempty"`
	ProjectDir string `json:"project_directory,omitempty"`
	HostName   string `json:"host_name,omitempty"`
	ReadSeq    int64  `json:"read_seq"`
}

GroupMember 是群成员的展示信息。

type GroupSummary

type GroupSummary struct {
	ID           string    `json:"id"`
	Title        string    `json:"title"`
	Archived     bool      `json:"archived"`
	MemberCount  int       `json:"member_count"`
	Unread       int       `json:"unread"`
	Mentioned    int       `json:"mentioned"` // 其中点名了你(或 @all)的条数
	Last         *Message  `json:"last,omitempty"`
	Preview      string    `json:"preview,omitempty"`
	CrossProject bool      `json:"cross_project"`
	UpdatedAt    time.Time `json:"updated_at"`
	// ProjectMembers 只在按项目过滤的列表里出现(项目页的「群聊」页签,#291):群里有几个(还没退出的)成员属于这个项目。
	ProjectMembers int `json:"project_members,omitempty"`
	// OtherMembers 同样只在按项目过滤的列表里出现:群里不属于这个项目的智能体成员数(来自别的项目、或不属于任何项目);没有就不出现。
	// MemberCount 含「你」自己,用它减 ProjectMembers 会把你算成「别处来的」,所以单独给这个数。
	OtherMembers int `json:"other_members,omitempty"`
	// contains filtered or unexported fields
}

GroupSummary 是会话列表里一个群的一行。

type Key

type Key struct {
	Ms   int64
	Rank int
	ID   string
}

Key 是消息在流里的完整排序键:(发送毫秒,来源序,主键)。

主键是来源表主键的字符串形式;数字主键补零到 12 位,字典序才与数值序一致。 同一毫秒内多条消息的先后由来源序再主键裁决,保证翻页稳定、不重不漏。

func ParseCursor

func ParseCursor(s string) (Key, error)

ParseCursor 解析 Encode 生成的游标。

func (Key) Encode

func (k Key) Encode() string

Encode 生成不透明游标(url 安全的 base64,不带填充)。

func (Key) Equal

func (k Key) Equal(o Key) bool

Equal 报告两个键是否相同。

func (Key) Less

func (k Key) Less(o Key) bool

Less 报告 k 是否排在 o 之前。

type ListParams

type ListParams struct {
	Limit  int
	Before string // 游标:取比它更早的(不含它)
	After  string // 游标:取比它更新的(不含它)
	Around string // 游标:取以它为中心的一窗(含它)
	Query  string // 子串搜索
	Kinds  []string
}

ListParams 是一次取消息的参数。Before / After / Around 互斥,优先级 Around > After > Before。

type MentionRef

type MentionRef struct {
	Ref  string `json:"ref"` // 工作流编号 | all | human
	Name string `json:"name"`
}

MentionRef 是消息里被点名的对象。

type Message

type Message struct {
	ID             string    `json:"id"`
	ConversationID string    `json:"conversation_id"`
	Kind           string    `json:"kind"`
	Sender         Sender    `json:"sender"`
	SentAt         time.Time `json:"sent_at"`
	// Cursor 是不透明游标(编码 发送毫秒 + 来源序 + 主键):翻页、已读、定位都用它。
	Cursor string `json:"cursor"`

	Title string `json:"title,omitempty"`
	Text  string `json:"text,omitempty"` // Markdown
	// Hash 是 8 位短哈希:别人(你)引用这条回复时写成「【回复 哈希】」;只有 Agent 的汇报与进度气泡有。
	Hash    string `json:"hash,omitempty"`
	ReplyTo string `json:"reply_to,omitempty"`

	Status   string     `json:"status"`
	StatusAt *time.Time `json:"status_at,omitempty"`

	Attachments []Attachment           `json:"attachments,omitempty"`
	Card        *model.ConfirmItemView `json:"card,omitempty"`
	Task        *TaskRef               `json:"task,omitempty"`
	Anchor      *Anchor                `json:"anchor,omitempty"`
	Decision    *DecisionGroup         `json:"decision,omitempty"`
	Source      Source                 `json:"source"`
	Hops        int                    `json:"hops"`
	Meta        map[string]any         `json:"meta,omitempty"`

	// 群消息专有(阶段 2b):点名了谁、谁读过了、被点名的成员各自的投递状态。
	Mentions   []MentionRef `json:"mentions,omitempty"`
	Reads      *ReadInfo    `json:"reads,omitempty"`
	Deliveries []Delivery   `json:"deliveries,omitempty"`
	// contains filtered or unexported fields
}

Message 是统一消息接口里的一条消息。

func (Message) IsFromAgent

func (m Message) IsFromAgent() bool

IsFromAgent 报告这条是不是 Agent 发的(已读游标与未读数只看它们)。

func (Message) Key

func (m Message) Key() Key

Key 返回消息的完整排序键。

type Page

type Page struct {
	ConversationID string    `json:"conversation_id"`
	Items          []Message `json:"items"`
	// BeforeCursor 是第一条的游标:往前翻页时作为 before 传回;AfterCursor 是最后一条的游标。
	BeforeCursor  string `json:"before_cursor,omitempty"`
	AfterCursor   string `json:"after_cursor,omitempty"`
	HasMoreBefore bool   `json:"has_more_before"`
	HasMoreAfter  bool   `json:"has_more_after"`
	// Unread 是你的已读游标之后 Agent 发的消息数(系统行不计);ReadMs 是游标本身(Unix 毫秒)。
	Unread int   `json:"unread"`
	ReadMs int64 `json:"read_ms"`
	// Agent 是这个会话里 Agent 一方的显示信息。
	Agent Sender `json:"agent"`
	// 群会话专有:群信息(含成员)与你在群里读到的序号。
	Group   *GroupInfo `json:"group,omitempty"`
	ReadSeq int64      `json:"read_seq,omitempty"`
}

Page 是一页消息(按发送时间升序)。

type ReadInfo

type ReadInfo struct {
	Read    int      `json:"read"`
	Total   int      `json:"total"`
	Readers []string `json:"readers,omitempty"`
	Unread  []string `json:"unread,omitempty"`
}

ReadInfo 是一条群消息的已读情况(G-3):N/M 与具体名单。

type ReadState

type ReadState struct {
	ReadMs int64 `json:"read_ms"`
	Unread int   `json:"unread"`
}

ReadState 是推进已读游标之后的结果。

type Sender

type Sender struct {
	Kind       string `json:"kind"`                  // human | agent | system
	ID         string `json:"id,omitempty"`          // human 恒为 "user";agent 是身份编号或 wf:<工作流>
	Name       string `json:"name"`                  // 显示名:你 / Agent 身份标签 / 系统
	WorkflowID string `json:"workflow_id,omitempty"` // agent 所属的工作流
}

Sender 是消息的发送者。

type Service

type Service struct {
	Store *store.Store
	// Now 可在测试里替换。
	Now func() time.Time
}

Service 把四个旧来源合成统一的消息流。

func NewService

func NewService(st *store.Store) *Service

NewService 创建服务。

func (*Service) Delivered

func (s *Service) Delivered(ctx context.Context, workflowID string, sess *model.FeedbackSession, queued *model.QueuedFeedback) (Message, error)

Delivered 把刚发出去的一次交付渲染成消息:Session 不为空是成了某一轮的回复,否则 Queued 是收件箱里排队的那条。

func (*Service) DigestForAgent

func (s *Service) DigestForAgent(ctx context.Context, workflowID string) ([]AgentGroupDigest, error)

DigestForAgent 列出某个工作流所在的群及各自的未读(只看入群之后的消息)。

func (*Service) GroupInfoOf

func (s *Service) GroupInfoOf(ctx context.Context, groupID string) (*GroupInfo, error)

GroupInfoOf 取群信息与成员。

func (*Service) GroupSummaries

func (s *Service) GroupSummaries(ctx context.Context, includeArchived bool) ([]GroupSummary, error)

GroupSummaries 列出群及未读(最近有动静的在前)。

func (*Service) List

func (s *Service) List(ctx context.Context, workflowID string, p ListParams) (*Page, error)

List 取一个工作流 1:1 会话的一页消息。

func (*Service) ListGroup

func (s *Service) ListGroup(ctx context.Context, groupID string, p ListParams) (*Page, error)

ListGroup 取一个群的一页消息(语义与 List 相同)。

func (*Service) ListSince

func (s *Service) ListSince(ctx context.Context, workflowID string, afterMs int64, n int) (items []Message, more bool, err error)

ListSince 取发送毫秒严格晚于 afterMs 的消息(升序,最多 n 条)。给 Agent 的读游标用:它没有消息游标,只有一个毫秒位置。

func (*Service) MarkGroupRead

func (s *Service) MarkGroupRead(ctx context.Context, groupID, cursor string) (ReadState, error)

MarkGroupRead 把你在群里的已读游标推到 cursor 对应的消息(空表示现在最新的一条)。

func (*Service) MarkRead

func (s *Service) MarkRead(ctx context.Context, workflowID, cursor string) (ReadState, error)

MarkRead 把你的已读游标推到 cursor 对应的消息(空表示现在)。游标只增不减,多设备取最大值。

func (*Service) PostAgent

func (s *Service) PostAgent(ctx context.Context, groupID, workflowID, text string, mentions []string, replyTo, idemKey string) (Message, *store.PostGroupResult, error)

PostAgent 以某个工作流的身份发一条群消息。

func (*Service) PostHuman

func (s *Service) PostHuman(ctx context.Context, groupID, text string, mentions []string, replyTo string) (Message, *store.PostGroupResult, error)

PostHuman 以你的身份发一条群消息。

func (*Service) ProjectGroupSummaries added in v2.2.0

func (s *Service) ProjectGroupSummaries(ctx context.Context, workflowIDs []string, includeArchived bool) ([]GroupSummary, error)

ProjectGroupSummaries 只列出「有成员属于这批工作流」的群(项目页的「群聊」页签,#291;workflowIDs 是项目的成员工作流)。 顺序、未读、点名与最后一条的口径与 GroupSummaries 完全一致(共用 summarizeGroup);每个群另带 ProjectMembers。 跨项目的群(成员来自几个项目)会出现在每个相关项目里,CrossProject 照常标出。没有成员工作流时返回空列表,不读群。

func (*Service) ReadForAgent

func (s *Service) ReadForAgent(ctx context.Context, groupID, workflowID string, afterSeq int64, limit int, peek bool) (*AgentRead, error)

ReadForAgent 取某个成员在群里还没读过的消息(只有入群之后、离开之前的);peek=false 时推进它的已读游标, 并把对应的 @ 提醒行标为已读取并确认。afterSeq > 0 时从这个序号之后取(不依赖游标)。

func (*Service) Summaries

func (s *Service) Summaries(ctx context.Context, workflowIDs []string) ([]Summary, error)

Summaries 取一批工作流的会话摘要(侧栏的最后一条预览与未读徽标)。

type Source

type Source struct {
	Type string `json:"type"`
	ID   string `json:"id"`
}

Source 标明一条消息来自哪张旧表的哪一行。

type Summary

type Summary struct {
	ID         string   `json:"id"`
	WorkflowID string   `json:"workflow_id"`
	Unread     int      `json:"unread"`
	Last       *Message `json:"last,omitempty"`
	Preview    string   `json:"preview,omitempty"`
}

Summary 是会话列表里一个 1:1 会话的一行:最后一条消息与未读数。

type TaskRef

type TaskRef struct {
	Seq       int    `json:"seq"`
	Title     string `json:"title"`
	State     string `json:"state"`
	FromState string `json:"from_state,omitempty"`
	ToState   string `json:"to_state,omitempty"`
}

TaskRef 是任务进展消息指向的任务。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL