store

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package store 是 SQLite 的唯一入口(AGENTS.md §2.1)。 业务包禁止直接写裸 SQL,全部经此 CRUD。本地单文件是唯一真相来源(§1.5)。

Index

Constants

View Source
const MaxSessionTags = 5

MaxSessionTags caps the per-session tag set (#150 MVP).

Variables

This section is empty.

Functions

func NormalizeTags

func NormalizeTags(tags []string) []string

NormalizeTags applies the write-layer rules (#150): trim each entry, drop empties, dedupe case-sensitively (exact match, idempotent), cap at MaxSessionTags preserving first-seen order.

Types

type McpServer

type McpServer struct {
	ID             string            `json:"id"`
	Name           string            `json:"name"`
	Transport      string            `json:"transport"` // "stdio" | "http" | "sse"
	Command        string            `json:"command"`   // stdio
	Args           []string          `json:"args"`      // stdio
	Env            map[string]string `json:"env"`       // stdio (plaintext; UI masks)
	URL            string            `json:"url"`       // http/sse
	Headers        map[string]string `json:"headers"`   // http/sse (plaintext; UI masks)
	DefaultEnabled bool              `json:"defaultEnabled"`
	CreatedAt      int64             `json:"createdAt"`
	UpdatedAt      int64             `json:"updatedAt"`
}

McpServer 一行 catalog:MCP server 的定义 + 默认开关。 transport 决定哪些字段有意义:stdio→Command/Args/Env;http/sse→URL/Headers。

type Message

type Message struct {
	ID         string `json:"id"`
	SessionID  string `json:"sessionId"`
	Role       string `json:"role"`
	Kind       string `json:"kind"`
	Content    string `json:"content"`
	ToolCallID string `json:"toolCallId,omitempty"`
	// TurnID/EntryKey: idempotent upsert keys for incremental turn persistence
	// (0017, #125). TurnID = the user message id that opened the turn;
	// EntryKey = timeline entry id. Empty = legacy rows (user messages /
	// pre-migration history) that don't participate in upsert dedupe.
	TurnID    string `json:"turnId,omitempty"`
	EntryKey  string `json:"entryKey,omitempty"`
	Seq       int64  `json:"seq"`
	CreatedAt int64  `json:"createdAt"`
}

Message 一条对话记录(role: user/agent/thought/tool)。

type PermissionRule

type PermissionRule struct {
	ID             string `json:"id"`
	ToolName       string `json:"toolName"`
	ActionType     string `json:"actionType"`
	PathPattern    string `json:"pathPattern"`
	CommandPattern string `json:"commandPattern"`
	Level          string `json:"level"` // allow | ask | deny
	SortOrder      int    `json:"sortOrder"`
	Enabled        bool   `json:"enabled"`
	CreatedAt      int64  `json:"createdAt"`
	UpdatedAt      int64  `json:"updatedAt"`
}

PermissionRule 一条权限规则(与 internal/permissions.Rule 对齐,§3.4)。 空约束字段 = 通配;AND 语义;按 SortOrder 升序逐条判定。

type Project

type Project struct {
	ID            string `json:"id"`
	Name          string `json:"name"`
	Path          string `json:"path"`
	Model         string `json:"model"`
	AllowExternal bool   `json:"allowExternalDir"` // 项目级权限记忆(§3.4):曾选「本项目允许」则该 project 所有 session(跨 harness)的 RequestPermission 自动放行
	SortOrder     int64  `json:"sortOrder"`        // 侧栏手动排序(0007):全 0 时兜底 updated_at DESC;拖拽后按 0..N-1 排。新建恒在顶部(MIN-1)
	CreatedAt     int64  `json:"createdAt"`
	UpdatedAt     int64  `json:"updatedAt"`
}

Project 一个项目(= 磁盘目录)。

type QueueItem

type QueueItem struct {
	ID          string `json:"id"`
	Text        string `json:"text"`
	Attachments string `json:"attachments"`
	ScheduledAt int64  `json:"scheduledAt"` // epoch ms; due when <= now
	// Recurring send (#111): RepeatEveryMs > 0 re-arms the item after each
	// successful send (skip-catch-up: next = max(now, prev+interval));
	// SentCount counts successful repeat sends; MaxSends 0 = unlimited,
	// N = auto-clear the repeat once SentCount reaches N.
	RepeatEveryMs int64 `json:"repeatEveryMs"`
	SentCount     int64 `json:"sentCount"`
	MaxSends      int64 `json:"maxSends"`
}

QueueItem is one persisted queue row. Attachments is the JSON-serialized attachment array ("" equivalent to empty).

func NewQueueItem

func NewQueueItem(text, attachmentsJSON string, scheduledAt int64) QueueItem

NewQueueItem builds a due-now row with a fresh id.

type Session

type Session struct {
	ID         string `json:"id"`
	ProjectID  string `json:"projectId"`
	ACPSession string `json:"acpSession"`
	Title      string `json:"title"`
	// CustomTitle is a user-defined rename, kept separate from the harness/auto-generated
	// Title so renaming never clobbers the original. Sidebar shows CustomTitle when set,
	// falling back to Title. Empty = no custom title (use Title).
	CustomTitle string `json:"customTitle"`
	Model       string `json:"model"`
	Harness     string `json:"harness"` // 使用的 harness(omp/opencode),新建会话时选择
	// session 的 git worktree(并行隔离用,§1.4)。空 = 非 git 项目或未建,直接用项目目录。
	WorktreePath string `json:"worktreePath"`
	Branch       string `json:"branch"`
	// BaseRef 基线分支(新建 worktree 时的起点 + 合并时的终点),空=非 worktree 或旧 session。
	// 显式基线,绝不裸用 HEAD(§1.4 todo/worktree-base-ref-selection.md)。
	BaseRef string `json:"baseRef"`
	// token 用量(最后一次 SessionUsageUpdate 的快照,使重开会话能恢复占比,§1.6)。
	UsedTokens int64   `json:"usedTokens"`
	SizeTokens int64   `json:"sizeTokens"`
	Cost       float64 `json:"cost"`
	// token 明细(来自 PromptResponse.Usage,UNSTABLE;Task #15138)。
	// streaming UsageUpdate 只含 used/size/cost,明细只在 Prompt 返回后回填。多数 harness 不回填则全 0。
	CachedReadTokens  int64 `json:"cachedReadTokens"`
	CachedWriteTokens int64 `json:"cachedWriteTokens"`
	InputTokens       int64 `json:"inputTokens"`
	OutputTokens      int64 `json:"outputTokens"`
	ThoughtTokens     int64 `json:"thoughtTokens"`
	TotalTokens       int64 `json:"totalTokens"`
	// ConfigOptionsCache:持久化的 config options 快照(懒 spawn:只读态渲染 ModelSelect 用)。
	// JSON 序列化的扁平化 []acp.ConfigOption。spawn/config_option_update/set_config_option 时回写。
	ConfigOptionsCache string `json:"configOptionsCache,omitempty"`
	CreatedAt          int64  `json:"createdAt"`
	UpdatedAt          int64  `json:"updatedAt"`
	PromptedAt         int64  `json:"promptedAt"` // 用户最后一次发消息的时刻,专用于侧栏排序(后台活动不刷新它)
	Pinned             bool   `json:"pinned"`     // 置顶(0008):置顶后恒在项目会话列表顶部;排序见 ListSessions
	// Tags user labels (0021, #150 MVP): stored as a JSON string array, read
	// back as []string. Pure organizational metadata, never a sort key; writes
	// go through NormalizeTags (trim / dedupe / cap 5) first.
	Tags []string `json:"tags"`
	// CommandsCache:persisted harness-advertised slash command table (#152). JSON of the
	// flattened []acp.SlashCommand; ” = never seeded, '[]' = seeded but zero commands.
	// Written on every available_commands_update (full-table replace, empty allowed) by the
	// handler via the service callback; read back for the lazy-spawn read-only slash menu.
	CommandsCache string `json:"commandsCache,omitempty"`
	// ForkedFrom:DB session id this session was forked from (0023, #172 Phase 2).
	// Empty = not a fork. Lineage only this phase — no UI marking, no cascade
	// semantics; the fork shares the source's worktree (same-cwd fork).
	ForkedFrom string `json:"forkedFrom,omitempty"`
	// ForkBaseSeq:the source session's max message seq at fork time (0024,
	// #172 Phase 3). The fork's transcript = source messages seq <= ForkBaseSeq
	// plus its own messages (lineage query, no copies). 0 = no watermark
	// (non-fork, or a pre-v24 fork row).
	ForkBaseSeq int64 `json:"forkBaseSeq,omitempty"`
}

Session 一个 ACP session(钉在 project 上)。

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store 封装 SQLite 连接。

func New

func New(dbPath string) (*Store, error)

New 打开(或创建)SQLite 并跑迁移。dbPath 为空时用内存库(测试用)。

func (*Store) AppendMessage

func (s *Store) AppendMessage(ctx context.Context, sessionID, role, kind, content, toolCallID string) (*Message, error)

AppendMessage 追加一条消息(seq 自增)。role: user/agent/thought/tool。

func (*Store) ClearWorktreeRefsByPath

func (s *Store) ClearWorktreeRefsByPath(ctx context.Context, projectID, worktreePath, keepSessionID string) error

ClearWorktreeRefsByPath clears the worktree ref (worktree_path/branch/base_ref) on every session mounted at worktreePath, except keepSessionID. Used to detach guests back to the project dir (history kept) when the owner deletes the worktree.

func (*Store) Close

func (s *Store) Close() error

Close 关闭数据库。

func (*Store) CreateMcpServer

func (s *Store) CreateMcpServer(ctx context.Context, m McpServer) (*McpServer, error)

CreateMcpServer 新建一行 catalog。id 由本方法生成(uuid)。name 重复 → SQLite UNIQUE 报错。 transport 必须是 stdio/http/sse;调用方据此填对应字段(无关字段传零值即可)。

func (*Store) CreatePermissionRule

func (s *Store) CreatePermissionRule(ctx context.Context, r PermissionRule) (*PermissionRule, error)

CreatePermissionRule 新建一条规则(id 由调用方给出或自动生成)。返回创建后的规则。

func (*Store) CreateProject

func (s *Store) CreateProject(ctx context.Context, name, path, model string) (*Project, error)

CreateProject 新建项目(path 唯一)。model 为空则用默认。

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, projectID, title, model, harnessv string) (*Session, error)

CreateSession 新建 session(钉在 project 上)。model 为空用项目默认;harness 为空用默认 harness(omp)。

func (*Store) CreateUserHarness

func (s *Store) CreateUserHarness(ctx context.Context, id, name, command, icon string) (*UserHarness, error)

CreateUserHarness 新建一个用户 harness。id 由调用方给(避免与内置冲突,已在 service 层校验)。 icon 空串合法(走兜底)。返回带 created_at 的完整行。id 已存在 → SQLite UNIQUE 约束报错。

func (*Store) DeleteMcpServer

func (s *Store) DeleteMcpServer(ctx context.Context, id string) error

DeleteMcpServer 删除一行 + 同步清理 session_mcp 里对它的引用(幂等)。

func (*Store) DeletePermissionRule

func (s *Store) DeletePermissionRule(ctx context.Context, id string) error

DeletePermissionRule 按 id 删除一条规则。

func (*Store) DeleteProject

func (s *Store) DeleteProject(ctx context.Context, id string) error

DeleteProject 删除项目(级联删 session + message)。

func (*Store) DeleteSession

func (s *Store) DeleteSession(ctx context.Context, id string) error

DeleteSession 删除 session(级联删 message)。

func (*Store) DeleteUserHarness

func (s *Store) DeleteUserHarness(ctx context.Context, id string) error

DeleteUserHarness 删除一个用户 harness。不存在不算错(幂等)。

func (*Store) GetMcpServer

func (s *Store) GetMcpServer(ctx context.Context, id string) (*McpServer, error)

GetMcpServer 取单行;不存在返回 nil, nil。

func (*Store) GetProject

func (s *Store) GetProject(ctx context.Context, id string) (*Project, error)

GetProject 取单个项目。

func (*Store) GetProjectByPath

func (s *Store) GetProjectByPath(ctx context.Context, path string) (*Project, error)

GetProjectByPath 按 path 取项目(去重用)。

func (*Store) GetSession

func (s *Store) GetSession(ctx context.Context, id string) (*Session, error)

GetSession 取单个 session。

func (*Store) GetSessionMcpServers

func (s *Store) GetSessionMcpServers(ctx context.Context, sessionID string) ([]McpServer, error)

GetSessionMcpServers 取某 session 选用的 MCP server(关联 catalog,按 name 升序)。 是 startLive 注入 session/new|resume 的数据源。session 无选择 → 空切片(非 nil)。

func (*Store) GetSetting

func (s *Store) GetSetting(ctx context.Context, key string) (string, error)

GetSetting 取配置值;无则返回空串。

func (*Store) GetUserHarness

func (s *Store) GetUserHarness(ctx context.Context, id string) (*UserHarness, error)

GetUserHarness 取单个用户 harness;不存在返回 nil, nil(调用方按内置回退)。

func (*Store) ListAllSessions

func (s *Store) ListAllSessions(ctx context.Context) (map[string][]Session, error)

ListAllSessions lists every project's sessions in one query, grouped by project id — the boot fast path replacing one ListSessions round-trip per project (request-storm fix step 3).

Per-project ordering is identical to ListSessions (pinned DESC, prompted_at DESC, updated_at DESC); rows tying on all three keys keep SQLite's scan order within their bucket, same as the per-project query.

Contract: the map has a key for EVERY project and values are always non-nil — 0-session projects map to an empty slice. A nil slice would marshal to JSON null and break the frontend invariant that every sessionsByProject value is an array.

func (*Store) ListDefaultMcpServers

func (s *Store) ListDefaultMcpServers(ctx context.Context) ([]McpServer, error)

ListDefaultMcpServers 列出 default_enabled=1 的 catalog 行(NewSession 预勾来源)。

func (*Store) ListMcpServers

func (s *Store) ListMcpServers(ctx context.Context) ([]McpServer, error)

ListMcpServers 列出全部 catalog 行(name 升序,稳定顺序便于 UI)。

func (*Store) ListMessages

func (s *Store) ListMessages(ctx context.Context, sessionID string) ([]Message, error)

ListMessages 列出某 session 全部消息(按 seq 升序)。

func (*Store) ListMessagesBefore

func (s *Store) ListMessagesBefore(ctx context.Context, sessionID string, beforeSeq int64, limit int) ([]Message, error)

ListMessagesBefore 游标分页:取 seq < beforeSeq 的最新 limit+1 条(beforeSeq<=0 取最新一页)。 多取 1 条用于判断 hasMore;返回按 seq 升序(与 ListMessages 一致)。前端据此 slice + 判断。

func (*Store) ListMessagesUpToSeq

func (s *Store) ListMessagesUpToSeq(ctx context.Context, sessionID string, maxSeq int64) ([]Message, error)

ListMessagesUpToSeq lists a session's messages with seq <= maxSeq, in seq ascending order (same shape as ListMessages). Powers the fork lineage transcript: the fork's shared prefix is the source's messages up to the recorded watermark. maxSeq <= 0 returns nothing (no watermark, no prefix).

func (*Store) ListPermissionRules

func (s *Store) ListPermissionRules(ctx context.Context) ([]PermissionRule, error)

ListPermissionRules 按优先级(sort_order ASC)列出全部权限规则。

func (*Store) ListProjects

func (s *Store) ListProjects(ctx context.Context) ([]Project, error)

ListProjects 列出全部项目(按 sort_order ASC, updated_at DESC):全 0 时兜底 updated_at DESC(原行为不变),拖拽后按手动顺序。

func (*Store) ListQueueItems

func (s *Store) ListQueueItems(ctx context.Context, sessionID string) ([]QueueItem, error)

ListQueueItems returns the session's queue in FIFO order (empty slice when none — never nil, so callers get a stable array shape).

func (*Store) ListSessions

func (s *Store) ListSessions(ctx context.Context, projectID string) ([]Session, error)

ListSessions 列出某项目的全部 session。 排序:pinned DESC(置顶恒在顶)→ prompted_at DESC(用户最后发消息时间)→ updated_at DESC(二级兜底)。 列表投影(sessionListColumns):不携带两个按需加载的缓存列。

func (*Store) ListUserHarnesses

func (s *Store) ListUserHarnesses(ctx context.Context) ([]UserHarness, error)

ListUserHarnesses 列出全部用户 harness(按 created_at ASC,稳定顺序;内置项在前由合并层保证)。

func (*Store) ListUserMessages

func (s *Store) ListUserMessages(ctx context.Context, sessionID string) ([]string, error)

ListUserMessages 列出某 session 全部用户消息的文本内容(按 seq 升序,无长度限制)。 供输入框「上下键翻历史」用:翻遍该 session 所有发过的消息。

func (*Store) MaxSessionMessageSeq

func (s *Store) MaxSessionMessageSeq(ctx context.Context, sessionID string) (int64, error)

MaxSessionMessageSeq returns the session's current max message seq (0 when the session has no messages). Powers the fork watermark (#172 Phase 3): the value captured at fork time bounds the fork's lineage query into the source.

func (*Store) ReorderPermissionRules

func (s *Store) ReorderPermissionRules(ctx context.Context, ids []string) error

ReorderPermissionRules 按传入 id 顺序全量重写 sort_order 为 0..N-1(拖拽后调用)。

func (*Store) ReorderProjects

func (s *Store) ReorderProjects(ctx context.Context, ids []string) error

ReorderProjects 按传入 id 顺序全量重写 sort_order 为 0..N-1(侧栏拖拽后调用)。 项目量级小(几十),事务内逐条 UPDATE,全量重写最简单可靠,无需 lexorank/浮点。

func (*Store) ReplaceQueueItems

func (s *Store) ReplaceQueueItems(ctx context.Context, sessionID string, items []QueueItem) error

ReplaceQueueItems atomically rewrites the session's queue; position = slice index. items == nil/empty clears the queue. Unknown sessionID fails on the FK constraint (file DBs; the caller validates existence where it matters).

func (*Store) SearchSessionIDsByContent

func (s *Store) SearchSessionIDsByContent(ctx context.Context, projectID, query string) ([]string, error)

SearchSessionIDsByContent 返回某项目下消息内容包含 query(大小写不敏感)的 session id 去重列表。 供侧栏会话搜索:桌面级 SQLite 单项目 LIKE 扫描是毫秒级,无需 FTS5。 返回 id 列表,前端在已加载的 session 列表上与标题命中做并集过滤(KISS:只回 id,不回 snippet)。 注意:query 中的 %/_ 会作 LIKE 通配符,桌面搜索场景可接受。

func (*Store) SeedDefaultPermissionRules

func (s *Store) SeedDefaultPermissionRules(ctx context.Context, defaults []PermissionRule) (bool, error)

SeedDefaultPermissionRules 表空时写入默认规则(§3.4)。返回是否写了。 默认规则来自调用方传入(避免 store 依赖 internal/permissions 包,反向依赖)。

func (*Store) SessionHasMessages

func (s *Store) SessionHasMessages(ctx context.Context, sessionID string) (bool, error)

SessionHasMessages 报告某 session 是否已有消息。 用于懒 spawn 判定:历史会话(有消息)只读打开,不 spawn harness(§3.x 懒 spawn)。

func (*Store) SessionsByWorktreePath

func (s *Store) SessionsByWorktreePath(ctx context.Context, projectID, worktreePath string) ([]Session, error)

SessionsByWorktreePath lists every session mounted at worktreePath under projectID (the owner + its guests). Powers WorktreeGuests (find guests) and the delete flow.

func (*Store) SetProjectAllowExternal

func (s *Store) SetProjectAllowExternal(ctx context.Context, id string, allow bool) error

SetProjectAllowExternal 设置项目级权限记忆(用户在权限弹窗选「本项目允许」时写)。 按 project 存、不分 harness → 跨 harness 共享;session 启动时由 service 读出加载进 handler(Handler.SetProjectAllowExternal),命中即对所有后续 RequestPermission 自动放行。 列名 allow_external_dir 保留历史(曾仅管外部目录),语义已泛化为「项目已批准」。

func (*Store) SetSessionBaseRef

func (s *Store) SetSessionBaseRef(ctx context.Context, id, baseRef string) error

SetSessionBaseRef 记录 session 的基线分支(worktree 基线解析后调)。

func (*Store) SetSessionForkBaseSeq

func (s *Store) SetSessionForkBaseSeq(ctx context.Context, id string, seq int64) error

SetSessionForkBaseSeq records the fork watermark (0024, #172 Phase 3): the source session's max message seq at fork time. Written together with forked_from in the same fork flow. 0 = unset.

func (*Store) SetSessionForkedFrom

func (s *Store) SetSessionForkedFrom(ctx context.Context, id, forkedFrom string) error

SetSessionForkedFrom records the fork lineage (0023, #172 Phase 2): the DB session id this session was forked from. Write-once at fork time; empty on non-fork sessions. Lineage is metadata, not content activity → updated_at untouched (same rationale as pinned 0008 / custom_title 0016 / tags 0021).

func (*Store) SetSessionMcp

func (s *Store) SetSessionMcp(ctx context.Context, sessionID string, serverIDs []string) error

SetSessionMcp 全量重写某 session 的 MCP 选择:删旧 → 插新(传入的 id 列表)。 空列表 = 该 session 不用任何 MCP(合法)。在 CreateSession 时调用。

func (*Store) SetSessionPinned

func (s *Store) SetSessionPinned(ctx context.Context, id string, pinned bool) error

SetSessionPinned 设置置顶(0008)。置顶不是内容活动 → 不动 updated_at(避免影响「时间」显示与二级排序)。 pinned 由 ListSessions ORDER BY pinned DESC 接管顶部位置;前端乐观本地重排即可即时生效。

func (*Store) SetSessionWorktree

func (s *Store) SetSessionWorktree(ctx context.Context, id, worktreePath, branch string) error

SetSessionWorktree 记录 session 的 git worktree 路径与分支(创建 worktree 后调)。

func (*Store) SetSetting

func (s *Store) SetSetting(ctx context.Context, key, value string) error

SetSetting 设置配置值。

func (*Store) TouchProject

func (s *Store) TouchProject(ctx context.Context, id string) error

TouchProject 更新项目的 updated_at(有新活动时)。

func (*Store) TouchPrompted

func (s *Store) TouchPrompted(ctx context.Context, id string) error

TouchPrompted 刷新 prompted_at(用户发消息时调)。它是侧栏主排序键,后台活动不刷新它, 保证侧栏顺序由用户意图掌控。

func (*Store) TouchSession

func (s *Store) TouchSession(ctx context.Context, id string) error

TouchSession 更新 updated_at。

func (*Store) UpdateMcpServer

func (s *Store) UpdateMcpServer(ctx context.Context, m McpServer) (int64, error)

UpdateMcpServer 全量更新一行(按 id;name 不可改——它是 server 标识,改了等于换 server)。 实际允许改 transport/连接字段/default_enabled。返回受影响行数:0=id 不存在。

func (*Store) UpdatePermissionRule

func (s *Store) UpdatePermissionRule(ctx context.Context, r PermissionRule) error

UpdatePermissionRule 全量更新一条规则(按 id)。enabled/level/各约束字段均来自入参。

func (*Store) UpdateProject

func (s *Store) UpdateProject(ctx context.Context, id, name, model string) error

UpdateProject 更新项目的 name/model。

func (*Store) UpdateSessionACP

func (s *Store) UpdateSessionACP(ctx context.Context, id, acpSessionID, title string) error

UpdateSessionACP 记录 opencode 返回的 session id(Resume 用,§1.4)。

func (*Store) UpdateSessionCommandsCache

func (s *Store) UpdateSessionCommandsCache(ctx context.Context, id, cacheJSON string) error

UpdateSessionCommandsCache replaces the persisted slash command table (#152). cacheJSON is the JSON of the flattened []acp.SlashCommand. Full-table replace semantics: the empty list is a legitimate write (JSON []); the zero value (empty string) means the harness has not advertised a table for it yet. Cache maintenance is not content activity, so updated_at stays untouched (same rationale as tags 0021; a mid-turn re-advertisement must not churn the sidebar secondary sort).

func (*Store) UpdateSessionConfigOptionsCache

func (s *Store) UpdateSessionConfigOptionsCache(ctx context.Context, id, cacheJSON string) error

UpdateSessionConfigOptionsCache 回写 config options 快照(懒 spawn:只读态渲染 ModelSelect 用)。 cacheJSON 为扁平化 []acp.ConfigOption 的 JSON。空串清空缓存。

func (*Store) UpdateSessionCustomTitle

func (s *Store) UpdateSessionCustomTitle(ctx context.Context, id, customTitle string) error

UpdateSessionCustomTitle sets the user-defined rename (0016). Empty clears it so the sidebar falls back to the auto-generated Title. Rename is not content activity, so it does not touch updated_at (keeps time display + secondary sort stable, like pinned).

func (*Store) UpdateSessionModel

func (s *Store) UpdateSessionModel(ctx context.Context, id, model string) error

UpdateSessionModel 更新 session 的 model(首条消息前在 model selector 改 model 时写库; 首条消息 NewSession 后改走 session/set_config_option 热切)。

func (*Store) UpdateSessionTags

func (s *Store) UpdateSessionTags(ctx context.Context, id string, tags []string) error

UpdateSessionTags replaces the session's tag set (0021). Input is normalized (trim / dedupe / cap 5) before persisting as a JSON array; an empty result clears all tags. Tag edits are not content activity → updated_at untouched (same rationale as pinned 0008 / custom_title 0016).

func (*Store) UpdateSessionTitle

func (s *Store) UpdateSessionTitle(ctx context.Context, id, title string) error

UpdateSessionTitle 更新 session 标题。

func (*Store) UpdateSessionTokens

func (s *Store) UpdateSessionTokens(ctx context.Context, id string, cachedRead, cachedWrite, input, output, thought, total int64) error

UpdateSessionTokens 回写 token 明细(来自 PromptResponse.Usage,Task #15138)。 与 UpdateSessionUsage(used/size/cost,streaming)分离:明细只在 Prompt 返回后更新, streaming UsageUpdate 不含明细;两者独立写、互不覆盖。

func (*Store) UpdateSessionUsage

func (s *Store) UpdateSessionUsage(ctx context.Context, id string, used, size int64, cost float64) error

UpdateSessionUsage 回写 token 用量快照(used/size/cost),使重开会话能恢复占比(§1.6)。

func (*Store) UpdateUserHarness

func (s *Store) UpdateUserHarness(ctx context.Context, id, name, command string) (int64, error)

UpdateUserHarness 改一个用户 harness 的 name + command(id 不变 —— session 钉在 id 上, 改 id 会断开既有 session 的关联)。name 空则兜底为 id(与 Create 一致)。返回受影响行数: 0 表示该 id 不存在(调用方应先 GetUserHarness 校验存在性)。

func (*Store) UpsertTurnMessage

func (s *Store) UpsertTurnMessage(ctx context.Context, sessionID, turnID, entryKey, role, kind, content, toolCallID string) (*Message, error)

UpsertTurnMessage idempotently writes one in-turn message (#125, the single write entry point for incremental turn persistence). Keyed by (session_id, turn_id, entry_key) (partial unique index, 0017):

  • First write: INSERT with seq = MAX(seq)+1 within the session (same ordering as AppendMessage).
  • Replays: in-place UPDATE of content/role/kind/tool_call_id/created_at; seq stays put — the row keeps the position of its first appearance (the timeline only appends, never shifts, §5.4 #5). created_at refreshes on every write: the turn-end reconcile always writes the final full text last, so the stored timestamp converges to turn end — the same time semantics as the old write-everything-at-turn-end behavior (frontend #68 relies on "last message ts = turn end").

turnID/entryKey must be non-empty (an empty key sits outside the partial index and can never hit the upsert branch); the caller (internal/chat) guarantees this, no defensive fallback here. Legacy rows (entry_key=”) are unaffected.

type UserHarness

type UserHarness struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Command   string `json:"command"`
	Icon      string `json:"icon"` // 空走通用兜底
	CreatedAt int64  `json:"createdAt"`
}

UserHarness 用户自添加 harness 一行(只存静态元数据)。 运行时数据(安装路径/版本/升级)由 harness.Discover 在合并视图上统一填,不在此存。

Jump to

Keyboard shortcuts

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