chat

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventUpdate      = "chat:event"       // SessionEvent(流式 chunk / tool / usage)
	EventPermission  = "chat:permission"  // PermissionPrompt(需用户裁决)
	EventElicitation = "chat:elicitation" // ElicitationPrompt(需用户填表单/选择,ACP v1 标准协议)
	// EventElicitationResolved:一次 elicitation 在「无用户操作」下被终结(超时降级 decline /
	// ctx 取消)。前端据此清残留卡片 —— 否则卡片最多残留 permTTL,期间点击后端报 no pending。
	EventElicitationResolved = "chat:elicitation-resolved"
	EventStatus              = "chat:status"       // StatusPayload(会话状态:started/prompting/idle/error/closed)
	EventSessionMeta         = "chat:session-meta" // SessionMetaPayload(标题等元信息更新)
	// EventQueue: QueuePayload — a full authoritative snapshot of a session's
	// server-side message queue (#126A, queue.go). Emitted on every mutation
	// (enqueue/revoke/edit/schedule/reorder/drain-dequeue) and on OpenSession;
	// the frontend is a degraded consumer that only renders what arrives here.
	EventQueue     = "chat:queue"
	EventHarnesses = "chat:harnesses" // harness 发现/版本变更(前端据此重拉 ListHarnesses)
	// EventHarnessCapabilities:harness 能力探测完成(ProbeCapabilities 后),前端据此重拉
	// ListHarnessCapabilities。异步触发(Discover 之后),独立于 EventHarnesses。
	EventHarnessCapabilities = "chat:harness-capabilities"
)

事件名(前端 Events.On 监听这些)。

View Source
const (
	// ErrCodeHarnessDisconnected:harness 崩溃/断连或 Prompt 失败,连接已重置,正在/将自动重连。
	ErrCodeHarnessDisconnected = "harness_disconnected"
	// ErrCodeHarnessEmptyTurn:Prompt 成功返回但零输出。end_turn 是协议合法返回,连接本身是好的,
	// 故只提示、不 teardown、不重连 —— 让用户可见地知道「本轮 agent 没回应」,连接保留可继续操作
	// (实测 omp /review 在无 elicitation 能力的 client 下命中:hasUI 误判 → 走交互菜单 → 静默空)。
	ErrCodeHarnessEmptyTurn = "harness_empty_turn"
	// ErrCodeHarnessReconnectFailed:断连后自动重连耗尽重试上限仍失败,需用户手动(发消息)触发再次尝试。
	ErrCodeHarnessReconnectFailed = "harness_reconnect_failed"
	// ErrCodeAgentTurnIncomplete:Prompt 成功返回、timeline 也非空,但 stopReason 不是 end_turn
	// (cancelled/refusal/max_tokens/max_turn_requests)——agent 自己没正常跑完这轮(常见:所选模型
	// 临时不可用、被拒绝、触上限)。harness 仍活、连接是好的,只推提示、不重连;用户可重试。
	ErrCodeAgentTurnIncomplete = "agent_turn_incomplete"
	// ErrCodeProviderQuotaExhausted: LLM provider quota/usage exhausted. The
	// failure arrives as the JSON-RPC error response, i.e. the harness process
	// is alive and the connection healthy (#46 probe §B) — NO teardown, NO
	// reconnect (respawning cannot restore quota); the payload carries ResetAt
	// (verbatim reset moment) and RootCause.
	ErrCodeProviderQuotaExhausted = "provider_quota_exhausted"
	// ErrCodeProviderTransient: transient provider/network error (429/5xx/
	// timeout/connection jitter) that still failed after the client-side
	// bounded auto-retry (N≤promptRetryLimit). Connection handling matches
	// other non-quota errors (teardown + reconnect on next message, #46 probe
	// §D regression boundary); the payload carries RootCause and Attempts.
	ErrCodeProviderTransient = "provider_transient_error"
	// ErrCodeElicitationUnrenderable(#158):elicitation form 扁平化后无可渲染字段
	// (fields==0),handler 已直接 Decline 给 harness。推 notice(非异常,连接正常,
	// 前端蓝色提示条)让用户知道该命令为何没有弹输入表单、直接空转结束。
	// Detail 留空:code 驱动 i18n(chat.notice.*),同 empty-turn 不变量。
	ErrCodeElicitationUnrenderable = "elicitation_unrenderable"
)

错误码(前端按 code 经 i18n 翻译,见 locales 的 chat.error.*)。

View Source
const EventFilesDropped = "chat:files-dropped"

EventFilesDropped is emitted to the frontend when the user drops OS files onto a data-file-drop-target element. Carries absolute paths + the target session id (read from the drop target's data-md-session attribute). The frontend routes per lib/dropFiles.ts.

View Source
const EventPopoutChanged = "chat:popout-changed"

EventPopoutChanged session 的 popout 状态变更(打开/关闭),前端据此刷新 poppedSessionIds。

Variables

This section is empty.

Functions

func AttachEmbeddedRemote

func AttachEmbeddedRemote(s *ChatService, tr *application.HTTPTransport, assets http.Handler, eventNames []string)

AttachEmbeddedRemote wires the transport + asset instances shared with the webview into an embedded remote server. Desktop builds call this before app.Run(); the server-tag build does not (build-tag split, same pattern as runDesktop). EventNames is the closed set of events bridged to clients. Package-level on purpose: a ChatService method would be picked up by the wails binding generator, which has no per-method exclusion.

func RegisterFilesDroppedEmitter

func RegisterFilesDroppedEmitter(win *application.WebviewWindow)

RegisterFilesDroppedEmitter wires a WindowFilesDropped handler on win that re-emits the dropped absolute paths as chat:files-dropped. The session id is read from the drop target element's data-md-session attribute (stamped on ChatView's root by the frontend), so the frontend can route to the right session without guessing from window focus. Used by both the main window (desktop.go) and popout windows (window.go) — the frontend scopes which window handles which session (popout owns its own; main skips popped-out).

No-op if win is nil; never returns an error. Drops only fire when the window was created with EnableFileDrop: true AND the cursor is over a [data-file-drop-target] element, so non-chat areas stay inert.

Types

type BrowseDirResult

type BrowseDirResult struct {
	Path   string        `json:"path"`
	Parent string        `json:"parent"`
	Dirs   []BrowseEntry `json:"dirs"`
}

BrowseDirResult is the BrowseDir response: the resolved directory, its parent (empty at the filesystem root, so the frontend knows to fall back to the roots view), and its immediate subdirectories.

type BrowseEntry

type BrowseEntry struct {
	Name string `json:"name"`
	Path string `json:"path"` // absolute path
}

BrowseEntry is one row of the web directory browser: a display name plus the absolute path it points at.

type ChatService

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

ChatService 暴露给前端的主服务。

func NewChatService

func NewChatService(cfg *config.Config) *ChatService

NewChatService 构造(尚未启动;ServiceStartup 时 open store)。

func (*ChatService) AddHarness

func (s *ChatService) AddHarness(command, name string) ([]harness.Harness, error)

AddHarness 添加用户自建 harness:命令派生 id → 冲突校验 → 落 SQLite → 刷内存合并视图 → Discover 刷新 → 异步能力探测。

id 由命令首段 basename 自动派生(用户不提供);name 可空(空则 store 兜底成 id)。 自检门槛:前端在调本 binding 前应已 ProbeNewHarness 通过(ConformanceReport.CanAdd 为真)。 本处不再服务端重跑 probe(探针含一轮完整 Prompt,90s+;前端已自检过,重跑既慢又费 token), 只做结构性校验(命令非空);派生 id 撞内置/已有用户时自动加 -2/-3 后缀消歧(id 对用户不可见)。

返回更新后的全量 harness 列表(前端据此刷新);error 非空时列表为 nil。

func (*ChatService) AddProject

func (s *ChatService) AddProject(name, path, model string) (*store.Project, error)

AddProject 新建项目。path 必须是已存在的目录。model 为空用默认。

func (*ChatService) BrowseDir

func (s *ChatService) BrowseDir(dir string) (*BrowseDirResult, error)

BrowseDir lists the immediate subdirectories of dir (an absolute path), sorted case-insensitively by name. Hidden (dot-prefixed) directories are included — the native picker shows them too, and project roots like ~/.config/... are legitimate picks (§5.3: no information loss). Symlinks that resolve to directories are descendable (broken ones are skipped), the same way native pickers treat them. The returned Path is the cleaned absolute path; Parent is empty when dir is the filesystem root. Read-only.

func (*ChatService) BrowseRoots

func (s *ChatService) BrowseRoots() ([]BrowseEntry, error)

BrowseRoots lists the starting locations for the web directory browser: the user's home directory first (where code projects usually live), then mounted volumes (macOS) or the filesystem root. Read-only.

func (*ChatService) CloseSession

func (s *ChatService) CloseSession(sessionID string) error

CloseSession 关闭活跃 ACP session(保留 db 记录,可再次 Open)。 busy(turn 进行中)时拒绝:idle reaper 跳过、用户需先 Stop。避免杀掉正在输出的 turn。 用户主动关 → 抑制自动重连(stopReconnect + giveUp),防在途重连把刚关的 session 又拉起来。

func (*ChatService) CloseSessionWindow

func (s *ChatService) CloseSessionWindow(sessionID string)

CloseSessionWindow 关闭某 session 的 popout 窗口(若存在)。「移回主窗口」用。

func (*ChatService) ContinueSession

func (s *ChatService) ContinueSession(sessionID string) error

ContinueSession 显式触发懒 spawn:只读态下用户点「继续会话」时调用, spawn harness(Resume 恢复历史会话 / NewSession 新会话)并切为可交互态。 已活跃则 no-op。与 SendMessage 共用 ensureLive(spawnMu 串行化,不双 spawn)。

func (*ChatService) CreateGuestSession

func (s *ChatService) CreateGuestSession(projectID, title, harnessID, enterPath string, mcpServerIDs []string) (*store.Session, error)

CreateGuestSession creates a session that ENTERS an existing worktree (a "guest"): no new worktree/branch is created — the session is pinned to enterPath (a live linked worktree). Multiple sessions can share one worktree (e.g. two agents collaborating / reviewing in the same dir). A guest only ever deletes its own chat; the worktree/branch belongs to the owner (DeleteWorktree). enterPath must be a current linked worktree of the project; its branch is resolved from git truth (not trusted from the caller). Non-git / main worktree / missing → error.

func (*ChatService) CreateMcpServer

func (s *ChatService) CreateMcpServer(m store.McpServer) (*store.McpServer, error)

CreateMcpServer 新增一个 MCP server 到 catalog。name 重复返回 error(前端提示换名)。

func (*ChatService) CreatePermissionRule

func (s *ChatService) CreatePermissionRule(rule store.PermissionRule) (*store.PermissionRule, error)

CreatePermissionRule 新建一条权限规则,并刷新所有活跃 session 的规则快照。

func (*ChatService) CreateSession

func (s *ChatService) CreateSession(projectID, title, harnessID string, useWorktree bool, baseRef string, mcpServerIDs []string) (*store.Session, error)

CreateSession 新建 session。harness 指定使用的 agent(omp/opencode,空=omp 默认); useWorktree=true 时为 git 项目建独立 worktree+分支(并行隔离),否则直接用项目目录(§1.4)。 baseRef:worktree 的基线分支(本地分支名,如 main/develop);useWorktree=true 时必填—— 空则后端探测默认(探测不到返回 errBaseRefRequired,Route A strict 不回退 HEAD); useWorktree=false 时忽略。

func (*ChatService) DeleteMcpServer

func (s *ChatService) DeleteMcpServer(id string) error

DeleteMcpServer 删除一个 MCP server(级联清理 session_mcp 引用)。

func (*ChatService) DeletePermissionRule

func (s *ChatService) DeletePermissionRule(id string) error

DeletePermissionRule 按 id 删除一条权限规则,并刷新所有活跃 session 的规则快照。

func (*ChatService) DeleteSession

func (s *ChatService) DeleteSession(sessionID string) error

DeleteSession deletes a session's chat + harness + DB row. It NEVER touches the worktree: worktree deletion is a separate atomic op (DeleteWorktree); the frontend orchestrates owner deletion (chat + DeleteWorktree) and the owner-with-guests 3-option dialog. Guests only ever delete their own chat — the worktree/branch belongs to the owner.

func (*ChatService) DeleteWorktree

func (s *ChatService) DeleteWorktree(sessionID string, force bool) error

DeleteWorktree removes the owner's worktree + branch (atomic; 4 guardrails in worktree.Remove). Owner-only: guest/project → error (no right to delete the worktree). The frontend calls this in the owner-delete flow (alone, or after DeleteSession/Detach).

Live-guest guard (#199): unless force, deletion is refused while other chats still reference the worktree — a guest would lose its cwd out from under it mid-chat. force=true skips ONLY this check (never the worktree.Remove guardrails); the frontend passes it from the owner-with-guests dialog's "delete all" option, where the user has already confirmed deleting every guest chat. The "keep" chain instead detaches the guests first (DetachWorktreeGuests), so the unforced guard passes naturally.

func (*ChatService) DetachWorktreeGuests

func (s *ChatService) DetachWorktreeGuests(sessionID string) error

DetachWorktreeGuests clears the worktree ref on every guest of the owner's worktree, so they fall back to the project dir while keeping their chat history. Used by the owner-delete "keep other conversations" option. The owner keeps its own ref (cleared by its DeleteSession).

func (*ChatService) EditQueueItem

func (s *ChatService) EditQueueItem(sessionID, itemID, text string) error

EditQueueItem updates a queued item's text in place (inline edit; schedule and attachments are kept).

func (*ChatService) EnqueueMessage

func (s *ChatService) EnqueueMessage(sessionID, text string, attachments []acp.Attachment) error

EnqueueMessage appends a message to the session's server-side queue. This is the parking path: a turn is running (frontend routes sends here while prompting) or the user explicitly enqueued (enqueue button / ⌘⇧Enter). It NEVER auto-starts a turn — drain fires at the next turn end (frontend parity: park only, so an explicit enqueue doesn't jump the gun). Enqueueing implies intent to continue → clears a pending stop intent.

func (*ChatService) ExpandSessionWindow

func (s *ChatService) ExpandSessionWindow(sessionID string)

ExpandSessionWindow 加宽 popout 窗口(右侧面板展开时调)。 不改高度,只加宽到 popoutWindowWidthExpanded,给 SidePanel 让出空间。

func (*ChatService) ExportSession

func (s *ChatService) ExportSession(sessionID, format string) (string, error)

ExportSession renders sessionID's full conversation to text. format: "jsonl" (one JSON per line) / "txt" (human-readable). Empty string is treated as "txt". The returned string is downloaded client-side via a Blob (the frontend composes the file name).

func (*ChatService) FocusSessionWindow

func (s *ChatService) FocusSessionWindow(sessionID string)

FocusSessionWindow 聚焦某 session 的 popout 窗口(若存在)。 供主窗口侧栏「已弹出」角标点击时调用:不重复开,只拉到前台。

func (*ChatService) ForkSession

func (s *ChatService) ForkSession(sourceSessionID string) (*store.Session, error)

ForkSession forks a session (#172 Phase 2): replicates the source ACP session at its CURRENT conversation end (the protocol has no position parameter) into a new harness-side session and creates a DB row for the fork.

Iron rules (probe 0cf4df6, docs/worklog/2026-08-31-fork-probe-172.md):

  • Gate on the DECLARED bit (sessionCapabilities.fork): undeclared → typed acp.ErrForkNotDeclared before any RPC. Wire error codes are diagnostics only — not assumed (-32603 was observed alongside the mainstream -32601).
  • Same-cwd fork (iron rule ②): the fork shares the source's worktree path; no new worktree, no baseRef. (A changed cwd is a deterministic omp error.)
  • Serial use (iron rule ③): a busy source (turn in flight) is rejected; after the fork, source and fork are NOT runtime-mutexed (known risk, worklog-documented; omp crashed on concurrent prompts).

The new row inherits project / model / harness / worktree from the source, carries forked_from = source id, and pins the fork response's OWN configOptions as the read-only model-select cache (consume-from-response per probe ⑤, never assume an echo). Title inheritance (#190): a renamed source hands its name down as custom_title+" (fork)" — immune to harness title churn, which only ever writes the title column; without a rename the legacy title+" (fork)" suffix lands in the title column.

func (*ChatService) GenerateRemotePairingCode

func (s *ChatService) GenerateRemotePairingCode() (code string, sid string, expiresAt string, err error)

GenerateRemotePairingCode issues a fresh one-time pairing attempt (10 min, single use) for browser clients: {6-digit code, pairing sid, expiry}. The sid binds the QR/link to THIS attempt — the code only works on the sid-bound entry page (2-of-2). Requires the remote server to be running.

func (*ChatService) GetAutoHarnessUpgrade

func (s *ChatService) GetAutoHarnessUpgrade() bool

GetAutoHarnessUpgrade 返回「自动升级 harness」开关当前值(前端设置面板复选框)。 store 未就绪(单测)时按默认 false,与启动默认一致。

func (*ChatService) GetCheckHarnessUpdates

func (s *ChatService) GetCheckHarnessUpdates() bool

GetCheckHarnessUpdates 返回「周期检查 harness 更新」开关当前值(前端设置面板复选框)。 store 未就绪(单测未启 ServiceStartup)时按默认 true,与启动默认一致。

func (*ChatService) GetConfig

func (s *ChatService) GetConfig() map[string]string

GetConfig 返回当前配置(默认 model、各数据目录)。

func (*ChatService) GetLastHarness

func (s *ChatService) GetLastHarness() string

GetLastHarness 返回上次新建对话选择的 harness(下次新建对话默认选中)。无则空串,前端自行回退首个。

func (*ChatService) GetPermissionTimeoutPolicy

func (s *ChatService) GetPermissionTimeoutPolicy() string

GetPermissionTimeoutPolicy 返回权限超时策略当前值("allow"/"deny";默认 deny)。 store 未就绪(单测)时按默认 deny,与启动默认一致(前端设置面板开关)。

func (*ChatService) GetRemoteInfo

func (s *ChatService) GetRemoteInfo() RemoteInfo

GetRemoteInfo returns the remote server state for the settings UI.

func (*ChatService) GetSessionCachedCommands

func (s *ChatService) GetSessionCachedCommands(sessionID string) ([]acp.SlashCommand, error)

GetSessionCachedCommands 返回 session 持久化的 slash 命令表快照(#152,懒 spawn 只读态 渲染 slash 菜单用)。语义与 GetSessionCachedConfigOptions 同构:空串 = 从未上报过(harness 还没广告过命令表)→ nil;JSON [] = 已上报但零命令 → 空切片;损坏 → nil(下次 spawn 会覆盖)。

func (*ChatService) GetSessionCachedConfigOptions

func (s *ChatService) GetSessionCachedConfigOptions(sessionID string) ([]acp.ConfigOption, error)

GetSessionCachedConfigOptions 返回 session 持久化的 config options 快照(懒 spawn:只读态渲染用)。 无缓存(空会话 / 从未 spawn 过 / 缓存损坏)返回 nil, nil —— 前端据此决定是否渲染 ModelSelect。

func (*ChatService) GetSessionConfigOptions

func (s *ChatService) GetSessionConfigOptions(sessionID string) ([]acp.ConfigOption, error)

GetSessionConfigOptions 返回当前 session 的 config options(给前端渲染下拉:model/mode/effort)。 懒 spawn:历史会话只读打开时未活跃 → 报错;spawn 后(发消息/继续会话)才可用。

func (*ChatService) GetSessionMcpServers

func (s *ChatService) GetSessionMcpServers(sessionID string) ([]store.McpServer, error)

GetSessionMcpServers 取某 session 选用的 MCP server(聊天头部只读状态 chip 用,§4.4)。 注意:只反映「选了哪些」(创建时定死),不反映实时连接状态(ACP 不回报,见 docs/worklog)。

func (*ChatService) GetSessionProjectID

func (s *ChatService) GetSessionProjectID(sessionID string) (string, error)

GetSessionProjectID 返回某 session 所属的 project ID。 供 popout 窗口启动时设 selectedProjectId(不依赖前端 sessionsByProject 的加载时序)。 session 不存在时返回空串(popout effect 据此跳过 openSession)。

func (*ChatService) GetSessionSnapshot

func (s *ChatService) GetSessionSnapshot(sessionID string) (string, error)

GetSessionSnapshot popout boot 时调用,取回主窗口打包的快照并立即删除(一次性)。 无快照或已取走返回空串(popout 回退为纯从 SQLite 加载)。

func (*ChatService) HasGitContext

func (s *ChatService) HasGitContext(projectID string) (bool, error)

HasGitContext reports whether the project has any usable git context for the SCM panel. This is the RELAXED counterpart to IsGitProject: true when proj.Path itself is a repo, OR when a (depth-limited, pruned) subdirectory is a repo (FindSubRepo fallback). The SCM panel routes through scmDir which already does this fallback, so its visibility flag must match that relaxed semantics — otherwise a wrapper project hides SCM even though changes can be surfaced from the sub-repo. Worktree gating must use IsGitProject (strict), not this.

func (*ChatService) ImportMcpConfig

func (s *ChatService) ImportMcpConfig(jsonData string) (McpImportResult, error)

ImportMcpConfig 一次性导入 harness 的 MCP 配置 JSON(自动识别 opencode mcp 段 / OMP mcpServers 段)。 这是「导入」不是「发现」:解析进 catalog 后文件即弃,SQLite 仍是唯一真相(§1.5)。 name 重复的跳过(不覆盖用户已改过的);逐条 Create,收集 added/skipped/warnings/errors。

func (*ChatService) InterruptAndSend

func (s *ChatService) InterruptAndSend(sessionID, text string, attachments []acp.Attachment) error

InterruptAndSend 打断当前 turn 并立即发送新消息(前端队列面板「立即发送」按钮)。 协议无 queue:turn 进行中发新消息的唯一正确做法 = session/cancel 当前 turn → 等其落定 → 发新 prompt。本方法把这几步原子化(sendMu 保护):

  • 置 suppressIdle:本轮 runPrompt 结束时不发 idle(否则前端 auto-continue 会误续发)
  • turnCancel:干净 session/cancel(SDK 自动发,非杀进程,连接保持可用)
  • <-turnDone:等本轮落定(persist 仍执行,partial 回复不丢)
  • startTurn:发新消息(发 prompting)

当前空闲时等价于 SendMessage。其余排队消息留在服务端队列,本方法不动(用户选「保留其余」)。

func (*ChatService) IsGitProject

func (s *ChatService) IsGitProject(projectID string) (bool, error)

IsGitProject reports whether the project directory itself is a git repo. This is the STRICT gate for worktree creation (§1.4): `git worktree add` operates on proj.Path as the repo, so a subdirectory being a repo does NOT qualify — the wrapper dir is not a repo and cannot spawn a worktree. Do not fold in FindSubRepo here.

func (*ChatService) IsSessionWindowPopped

func (s *ChatService) IsSessionWindowPopped(sessionID string) bool

IsSessionWindowPopped 报告某 session 是否已弹出到独立窗口。供前端 boot 时对账。

func (*ChatService) ListAllSessions

func (s *ChatService) ListAllSessions() (map[string][]store.Session, error)

ListAllSessions returns every project's sessions in one call, grouped by project id (boot fast path — replaces one ListSessions per project). The map carries a key for every project; 0-session projects map to an empty slice, never nil.

func (*ChatService) ListHarnessCapabilities

func (s *ChatService) ListHarnessCapabilities() map[string]acp.CapabilityMatrix

ListHarnessCapabilities 返回已探测 harness 的能力位快照(harnessID → CapabilityMatrix)。 启动后异步填充(Discover 之后);未就绪时返回 nil(前端按需展示「检测中」或不展示)。 前端监听 EventHarnessCapabilities 事件以在探测完成后重拉。

func (*ChatService) ListHarnesses

func (s *ChatService) ListHarnesses() []harness.Harness

ListHarnesses 返回当前已发现的 harness 列表(含本地安装版本与上游最新版本)。 启动后异步刷新;未就绪时回退静态 Supported(无版本信息,但前端能继续选 harness)。 前端监听 EventHarnesses 事件以在刷新后重拉。

func (*ChatService) ListMcpServers

func (s *ChatService) ListMcpServers() ([]store.McpServer, error)

ListMcpServers 列出全局 MCP catalog(name 升序)。设置面板 + NewSession 勾选用。

func (*ChatService) ListPermissionRules

func (s *ChatService) ListPermissionRules() ([]store.PermissionRule, error)

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

func (*ChatService) ListPoppedSessions

func (s *ChatService) ListPoppedSessions(sessionIDs []string) []string

ListPoppedSessions batch-reports which of the given sessions currently live in a popout window (boot reconcile fast path — replaces one IsSessionWindowPopped RPC per session). Same truth source as the singular variant: the WindowManager lookup by popout window name. Returns a non-nil slice (empty = none popped).

func (*ChatService) ListProjects

func (s *ChatService) ListProjects() ([]store.Project, error)

ListProjects 列出全部项目。

func (*ChatService) ListSessions

func (s *ChatService) ListSessions(projectID string) ([]store.Session, error)

ListSessions 列出某项目的全部 session。

func (*ChatService) ListUserMessages

func (s *ChatService) ListUserMessages(sessionID string) ([]string, error)

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

func (*ChatService) ListWorktrees

func (s *ChatService) ListWorktrees(projectID string) ([]worktree.WorktreeInfo, error)

ListWorktrees returns the project's git worktrees (main + linked) for the NewSessionModal "use existing directory" selector. Main (IsMain=true) is first; branch resolved from git.

func (*ChatService) LoadMessages

func (s *ChatService) LoadMessages(sessionID string) ([]store.Message, error)

LoadMessages returns a session's OWN messages (no lineage merge). It is not used to render a fork's transcript — that goes through LoadMessagesPage (forkLineagePage), which presents the fork's view as source prefix + its own messages. Kept as the raw-read helper for callers that want a session's real rows only.

func (*ChatService) LoadMessagesPage

func (s *ChatService) LoadMessagesPage(sessionID string, beforeSeq int64, limit int) ([]store.Message, error)

LoadMessagesPage 分页取历史消息(beforeSeq<=0 取最新一页)。返回 limit+1 条: 前端用 len > limit 判断 hasMore,多出的那条 slice 掉。首次打开 session 用此方法做懒加载。

#172 Phase 3 lineage view: a fork row's transcript = the SOURCE's messages up to the recorded watermark (fork_base_seq) followed by the fork's own. The base prefix is presented with NEGATIVE seq offsets (m.seq - watermark - 1 ∈ [-N,-1]) so the merged list is globally ascending under one cursor and the frontend's pagination (beforeSeq cursor, hasMore, prepend) works unchanged.

func (*ChatService) MatchKnownHarness

func (s *ChatService) MatchKnownHarness(command string) *harness.KnownHarness

MatchKnownHarness 按启动命令关键词匹配「已知 harness 目录」(harness.KnownCatalog), 返回最匹配项(nil = 无命中)。前端「添加 harness」弹窗:用户输入命令时实时调本 binding 自动选中有名 harness,据返回的 ID 展示图标(HarnessIcon 自行解析)并预填 Name(用户可覆盖)。 与 Supported 注册表(omp/opencode)无关 —— 这里只做已知的 README agent 目录匹配。

func (*ChatService) MergeSession

func (s *ChatService) MergeSession(sessionID string) (string, error)

MergeSession 把 session 分支已提交的内容合并进项目主仓库。 只 merge 已 commit 的内容(git merge 本就只合并 commit);未提交的改动不会进 merge —— 由源代码管理面板负责提交(精细 stage/commit 是 SCM 面板的职责,merge 不再越权 git add .)。 若 worktree 仍有未提交改动,结果里给出提示,让用户知道还有东西没合并。

func (*ChatService) OpenSession

func (s *ChatService) OpenSession(sessionID string) error

OpenSession 打开已有 session。懒 spawn(§3.x):

  • 历史会话(已有消息):只读打开,不 spawn harness —— 仅从 DB 读历史展示, 推 readonly 状态让前端给「只读 - 发消息以继续」提示。用户发新消息或点「继续会话」 (ContinueSession)时才 spawn 并切为可交互态。避免只读查看浪费一个 harness 进程。
  • 新建会话(无消息):保持原行为,立即异步 spawn(B 方案:切过去就绪,首条消息零延迟)。

立即返回(不阻塞前端加载历史,历史从 DB 读,独立于 harness)。ensureLive 的 spawnMu 串行化保证用户在 spawn 完成前发消息不会双 spawn。

func (*ChatService) OpenSessionWindow

func (s *ChatService) OpenSessionWindow(sessionID string) error

OpenSessionWindow 把某 session 弹到独立窗口(单例:已存在则聚焦,否则新建)。 前端在调用前应先 SaveSessionSnapshot 打包当前 React state,供 popout 还原。

func (*ChatService) OpenURL

func (s *ChatService) OpenURL(url string) error

OpenURL 用系统默认浏览器打开指定 URL。 供前端拦截 markdown 对话里的 http/https 外链点击后调用(Wails3 webview 不承担浏览器导航, 转交给系统浏览器)。仅处理 http/https,mailto/tel/内部锚点放行默认行为(前端判定)。

func (*ChatService) PickDirectory

func (s *ChatService) PickDirectory() (string, error)

PickDirectory 弹出原生目录选择对话框,返回选中路径(取消则返回空串)。 供前端「添加项目」时选取项目根目录。

func (*ChatService) PickFiles

func (s *ChatService) PickFiles() ([]string, error)

PickFiles 弹出原生多文件选择对话框,返回选中的文件绝对路径列表(取消则空)。 附件以 @/path 注入 prompt(opencode 据此读取具体文件),供前端 composer 附件功能。

func (*ChatService) ProbeNewHarness

func (s *ChatService) ProbeNewHarness(command string) (*acp.ConformanceReport, error)

ProbeNewHarness 对候选 harness 命令跑 ACP conformance 自检,返回体检单(ConformanceReport)。 前端「添加 harness」弹窗流程:填命令 → 自检(调本 binding)→ 展示体检单 → ConformanceReport.CanAdd 为真才允许点「添加」调 AddHarness。

严格门槛(见 acp.ProbeHarness):要求完整 end_turn —— 不仅证 ACP 契约健康, 还证该 harness 在当前环境真能跑完一轮(模型/key/网络就绪)。各步带硬超时,整体上限 3min (诊断场景的硬超时,与活 turn 的 §3.3 no-timeout 无关)。零 per-harness 身份分支。

func (*ChatService) RecentBaseRefs

func (s *ChatService) RecentBaseRefs(projectID string) ([]string, error)

RecentBaseRefs returns the project's recently-selected base branches (most-recent- first), filtered to refs that still exist. Powers the NewSessionModal "Recently used" group. Per-project (baseRefHistory:<id> setting, JSON array).

func (*ChatService) RefreshHarnesses

func (s *ChatService) RefreshHarnesses() ([]harness.Harness, error)

RefreshHarnesses 立即重新发现 harness 并查上游最新版本,更新缓存并返回。 用户在 harness 管理面板点「刷新」时调;比启动时的异步刷新慢但更完整(无短超时)。

func (*ChatService) RefreshSessionConfig

func (s *ChatService) RefreshSessionConfig(sessionID string) ([]acp.ConfigOption, error)

RefreshSessionConfig 重新拉取 session 的最新 configOptions(同步外部配置改动)。

用户在 harness 配置(如 opencode config)外部加了新 provider/model 后,点聊天界面的 「刷新」按钮触发此方法。后端 spawn 一个临时 probe harness(同 cwd + 同 harness 命令) 拉取最新 configOptions,更新到活跃 session 内存,并推 config_option event 让前端 模型下拉立即看到新选项。详见 acp.ChatSession.RefreshConfig。

probe 完全独立:不影响当前活跃连接、不中断进行中的对话流(哪怕 turn 正在跑)。 调用方应配超时(spawn harness 可能慢),失败返回错误供前端提示。

func (*ChatService) RegenerateRemoteToken

func (s *ChatService) RegenerateRemoteToken() (string, error)

RegenerateRemoteToken rotates the token; takes effect immediately for new requests (existing cookies stop validating). Returns the new token.

func (*ChatService) RemoteListSessions

func (s *ChatService) RemoteListSessions() []RemoteSessionInfo

RemoteListSessions returns the paired devices, newest first.

func (*ChatService) RemoteRevokeSession

func (s *ChatService) RemoteRevokeSession(id string) (bool, error)

RemoteRevokeSession kicks one paired device by session id.

func (*ChatService) RemoveProject

func (s *ChatService) RemoveProject(id string) error

RemoveProject 删除项目(同时关掉其活跃 session)。

func (*ChatService) ReorderPermissionRules

func (s *ChatService) ReorderPermissionRules(ids []string) error

ReorderPermissionRules 按传入 id 顺序重写优先级,并刷新所有活跃 session 的规则快照。

func (*ChatService) ReorderProjects

func (s *ChatService) ReorderProjects(ids []string) error

ReorderProjects 按传入 id 顺序重写项目排序(侧栏拖拽后调用,0007)。

func (*ChatService) ReorderQueueItem

func (s *ChatService) ReorderQueueItem(sessionID, activeID, overID string) error

ReorderQueueItem moves item activeID onto overID's position (remove, then insert at overID's index) — the drag-drop / mobile up-down semantics. While idle with a due first item, drains immediately (order changed which message goes next).

func (*ChatService) ResetPermissionRules

func (s *ChatService) ResetPermissionRules() error

ResetPermissionRules 清空全部规则并重写为默认规则(用户点「恢复默认」)。

func (*ChatService) ResolveBaseRefDefault

func (s *ChatService) ResolveBaseRefDefault(projectID string) (worktree.DefaultBaseRef, error)

ResolveBaseRefDefault returns the repo's detected default branch (origin/HEAD → main/master probe) for the NewSessionModal. It is pinned to the top of the selector as the "Default branch" group and starred. Detection failure → Ok=false (selector still works, just no Default group).

This NO LONGER pre-selects a base nor folds in the last selection: the user must pick a base explicitly (pre-selection caused wrong-base mistakes). Recent selections are surfaced separately via RecentBaseRefs. §1.4 explicit base, never silently fall back to HEAD.

func (*ChatService) RespondElicitation

func (s *ChatService) RespondElicitation(sessionID, reqID, action, contentJSON string) error

RespondElicitation 用户在前端对某 elicitation 提示做出响应(ACP v1 标准协议,§3.x elicitation)。 action: accept(提交 content)/ decline(拒绝)/ cancel(取消)。 contentJSON: accept 时表单字段的 JSON 字符串(如 '{"value":"selected"}');非 accept 传空串。 经 JSON 中转:Wails3 binding 生成器对 map[string]any 不生成 TS 类型,故用 string 传输 + 此处反序列化。

func (*ChatService) RespondPermission

func (s *ChatService) RespondPermission(sessionID, reqID, level string) error

RespondPermission 用户在前端对某权限请求做出裁决(§3.4)。 level: once(允许本次)/ session(本会话允许)/ project(本项目允许)/ deny(本次拒绝)。 session/project 档令该 handler 后续「所有 RequestPermission」自动放行;project 档另写库(按 project 存、跨 harness 持久)。

func (*ChatService) RevealPath

func (s *ChatService) RevealPath(path string) error

RevealPath 在系统文件管理器中打开指定路径(macOS Finder / Windows 资源管理器 / Linux xdg)。

func (*ChatService) RevokeQueueItem

func (s *ChatService) RevokeQueueItem(sessionID, itemID string) error

RevokeQueueItem removes one item from the queue. The frontend refills the composer from its event-synced copy of the item (the "revoke to edit" flow).

func (*ChatService) SaveSessionSnapshot

func (s *ChatService) SaveSessionSnapshot(sessionID, snapshotJSON string) error

SaveSessionSnapshot 主窗口在 OpenSessionWindow 前调用,打包当前 React state。 snapshotJSON 是前端序列化的 JSON(items/queue/draft/livePlan/permission 等)。

func (*ChatService) ScheduleQueueItem

func (s *ChatService) ScheduleQueueItem(sessionID, itemID string, scheduledAt int64) error

ScheduleQueueItem sets (or clears) a queued item's scheduledAt. <= 0 / now means "due immediately". Mirrors the old frontend behavior: changing the schedule while idle with the item now due sends it right away; a future time parks it until the one-shot timer fires.

func (*ChatService) SearchBaseRefs

func (s *ChatService) SearchBaseRefs(projectID string) ([]worktree.BranchInfo, error)

SearchBaseRefs 返回项目的本地+远程跟踪分支列表(供 NewSessionModal 基线选择器一次性拉取 + 前端过滤)。 排除 */HEAD 伪 ref,按 committerdate 倒序,封顶 200 条。todo §4.3。

func (*ChatService) SearchSessionContent

func (s *ChatService) SearchSessionContent(projectID, query string) ([]string, error)

SearchSessionContent 返回某项目下消息内容包含 query(大小写不敏感)的 session id 列表。 供侧栏会话搜索:与标题命中(前端本地子串)做并集,实现「按标题或内容找会话」(§4.1)。

func (*ChatService) SendAndWaitSync

func (s *ChatService) SendAndWaitSync(sessionID, text string, attachments []acp.Attachment) (string, error)

SendAndWaitSync sends a message synchronously and waits for the reply (for drivers/tests; the GUI uses the async SendMessage). Returns the agent text and error. Connection handling on failure matches runPrompt: quota exhaustion keeps the connection (harness alive and healthy, #46); every other failure tears it down, so the caller's retry reconnects via Resume in ensureLive (§5.4 #16).

func (*ChatService) SendMessage

func (s *ChatService) SendMessage(sessionID, text string, attachments []acp.Attachment) error

SendMessage 发送用户消息并驱动 opencode 回复(Prompt,§1.3)。 仅在 idle 时可用:协议规定一个 session 同时只允许一个 Prompt(§5.4 调研结论)。 turn 进行中时前端应把消息入服务端队列 EnqueueMessage(#126A,不调本方法);busy 守卫兜底防竞态。

func (*ChatService) ServiceShutdown

func (s *ChatService) ServiceShutdown() error

ServiceShutdown Wails3 关闭钩子:停 idle reaper + 关所有活跃 session + store。

func (*ChatService) ServiceStartup

func (s *ChatService) ServiceStartup(ctx context.Context, options application.ServiceOptions) error

ServiceStartup Wails3 启动钩子:建数据目录 + open store。

func (*ChatService) SessionAICommit

func (s *ChatService) SessionAICommit(sessionID string) error

SessionAICommit 让当前 session 的 agent 自动提交未提交改动(AI 提交,架构 A)。 复用 SendMessage 发送一段指令:agent 自己审视改动、生成提交信息并提交。 复用现有 turn 生命周期 / 权限 UI / 流式渲染,提交作为一轮对话显示在聊天里(可审计)。 仅 idle 可用(busy 由 SendMessage 守卫);无改动时 agent 会自行说明。

func (*ChatService) SessionChanges

func (s *ChatService) SessionChanges(sessionID string) ([]worktree.FileChange, error)

SessionChanges 返回该 session 的文件级变更列表(VS Code 风格:逐文件 + M/A/D/U 状态)。

func (*ChatService) SessionCommit

func (s *ChatService) SessionCommit(sessionID, message string) error

SessionCommit 提交已暂存的改动(只 commit index,不自动 add)。 提交是源代码管理面板的职责;MergeSession 只合并已提交内容,不再越权提交。

func (*ChatService) SessionCreateDir

func (s *ChatService) SessionCreateDir(sessionID, rel string) error

SessionCreateDir 在 session 工作目录下新建目录。

func (*ChatService) SessionCreateFile

func (s *ChatService) SessionCreateFile(sessionID, rel, content string) error

SessionCreateFile 在 session 工作目录下新建文件(含内容)。

func (*ChatService) SessionCurrentBranch

func (s *ChatService) SessionCurrentBranch(sessionID string) (string, error)

SessionCurrentBranch 返回 session 工作目录的当前分支(供源代码管理面板顶部展示)。 worktree 模式 = md/<id> 分支;非 worktree 的 git 项目 = 项目目录当前分支(detached HEAD 时为短 commit); 非 git 项目返回空串(前端不展示 SCM,分支位也无意义)。

关键:Branch 字段只在 worktree 模式有值(= md/<id>),非 worktree 恒空 —— 前端若直接读 session.Branch 会在非 worktree 的 git 项目里显示空分支。这里读真实 HEAD 修正该展示。

func (*ChatService) SessionDeletePath

func (s *ChatService) SessionDeletePath(sessionID, rel string) error

SessionDeletePath 删除 session 工作目录下的文件或目录(递归)。

func (*ChatService) SessionDiscard

func (s *ChatService) SessionDiscard(sessionID string, paths []string) error

SessionDiscard 丢弃工作区改动(已跟踪还原 / 未跟踪删除)。只作用于工作区,不动暂存区。

func (*ChatService) SessionFileDiff

func (s *ChatService) SessionFileDiff(sessionID, path string, staged bool) (string, error)

SessionFileDiff 返回单个文件的 unified diff(staged=true:已暂存相对 HEAD;否则工作区相对 index, 未跟踪文件展示为纯新增)。供源代码管理面板点击文件查看改动(VSCode SCM 风格)。

func (*ChatService) SessionFuzzyFind

func (s *ChatService) SessionFuzzyFind(sessionID, scope, query string, limit int) ([]fsview.FileNode, error)

SessionFuzzyFind 在 session 工作目录下按 query 子串模糊匹配路径,返回最多 limit 个命中。 scope 限定搜索子树(相对 cwd 的路径,空表示整棵 cwd 树),透传给 fsview.FuzzyFind。 git 仓库复用 fsview 可见集(尊重 .gitignore),非 git 目录跳过 .git / node_modules 等大目录。 文件与目录都参与匹配;空 query 返回 scope 的直接子项(含目录);limit<=0 用默认上限。 路径钉在 cwd(safeJoin 防越界)。

func (*ChatService) SessionListDir

func (s *ChatService) SessionListDir(sessionID, rel string) ([]fsview.FileNode, error)

SessionListDir 列出 session 工作目录下 rel(相对路径)的直接子项。 rel 为空表示根。路径钉在 cwd,防越界;git 仓库尊重 .gitignore。

func (*ChatService) SessionMergeable

func (s *ChatService) SessionMergeable(sessionID string) (bool, error)

SessionMergeable 报告该 session 是否有可合并内容(branch 有领先基线的已提交 commit)。 供前端在打开源代码管理面板时预检:无则 disable 合并按钮 + 提示「无需要合并的变更」。 只看已提交差异(merge 只合并 commit);未提交改动不在此判定(由 SCM 面板的 stage/commit 流程处理)。 非 worktree session(无基线/无分支)返回 false。

func (*ChatService) SessionReadFile

func (s *ChatService) SessionReadFile(sessionID, rel string) (fsview.FileData, error)

SessionReadFile reads the text content of rel under the session workdir (preview). Binary / too-large files return zero Content with the flag set.

func (*ChatService) SessionReadImage

func (s *ChatService) SessionReadImage(sessionID, rel string) (fsview.ImageData, error)

SessionReadImage 读取 session 工作目录下 rel 的图片,返回 dataURL(data:<mime>;base64,<b64>) 与扩展名(不含点)。路径钉在 cwd(safeJoin 防 ../ 与符号链接越界);非图片 / 过大 / 越界报错。

func (*ChatService) SessionRenamePath

func (s *ChatService) SessionRenamePath(sessionID, rel, newName string) (string, error)

SessionRenamePath 把 session 工作目录下的 rel 改名为 newName(叶子名)。 返回新的相对路径。

func (*ChatService) SessionStage

func (s *ChatService) SessionStage(sessionID string, paths []string) error

SessionStage 暂存文件;paths 为空暂存全部(供源码管理面板,参考 VS Code SCM)。 turn 进行中拒绝,避免与 opencode 写文件竞争 git index(§E 并发守卫)。

func (*ChatService) SessionStatuses

func (s *ChatService) SessionStatuses() map[string]string

SessionStatuses returns a read-only snapshot of every live session's current status. Remote clients (§1.8) whose WebSocket dropped mid-turn — or connected after a turn started — missed the chat:status push events; this pull API is the reconciliation channel behind remote:resync (issues #134/#127).

Status is derived from backend truth, not replayed event state:

  • busy turn in flight → "prompting"
  • auto-reconnect in progress → "reconnecting"
  • reconnect budget exhausted → "error"
  • otherwise (live but idle) → "idle"

Absence means "no live harness": a caller's cached "prompting" for an absent session is stale and must be dropped (the turn is definitively over).

func (*ChatService) SessionUnstage

func (s *ChatService) SessionUnstage(sessionID string, paths []string) error

SessionUnstage 取消暂存文件;paths 为空取消全部。

func (*ChatService) SessionWriteFile

func (s *ChatService) SessionWriteFile(sessionID, rel, content string) error

SessionWriteFile overwrites rel with content under the session workdir (the file preview's edit/save path). Path is pinned to the workdir.

func (*ChatService) SetAutoHarnessUpgrade

func (s *ChatService) SetAutoHarnessUpgrade(on bool) error

SetAutoHarnessUpgrade 设置「自动升级 harness」开关并实时启停后台 ticker: 开启即起周期 ticker(发现可升级且安全时静默 UpgradeHarness);关闭且 check 也关时停 ticker。 值持久化,重启后保持。

func (*ChatService) SetCheckHarnessUpdates

func (s *ChatService) SetCheckHarnessUpdates(on bool) error

SetCheckHarnessUpdates 设置「周期检查 harness 更新」开关并实时启停后台 ticker: 仅当 auto 也关闭时关 check 才会真正停 ticker。值持久化,重启后保持。

func (*ChatService) SetDefaultModel

func (s *ChatService) SetDefaultModel(model string) error

SetDefaultModel 设置全局默认 model(写 settings)。

func (*ChatService) SetPermissionTimeoutPolicy

func (s *ChatService) SetPermissionTimeoutPolicy(policy string) error

SetPermissionTimeoutPolicy 设置权限超时策略并持久化(重启后保持)。 活跃 session 不热更:策略在 startLive 装配时注入 handler,新会话/重启后生效。

func (*ChatService) SetQueueItemRepeat

func (s *ChatService) SetQueueItemRepeat(sessionID, itemID string, repeatEveryMs, maxSends int64) error

SetQueueItemRepeat sets, changes or clears an item's recurrence (#111): repeatEveryMs 0 turns it back into a normal one-shot item; a non-zero value must fall in [1min, 24h] (hard gate — outside is rejected with the stable errQueueRepeatInterval code). maxSends 0 = repeat forever, N = auto-clear the repeat once sentCount reaches N. The item's scheduledAt is untouched — recurrence only decides what happens AFTER each successful send, so the next fire time stays wherever the schedule (#97) put it.

func (*ChatService) SetRemoteEnabled

func (s *ChatService) SetRemoteEnabled(on bool) error

SetRemoteEnabled toggles the listener live (persist + start/stop).

func (*ChatService) SetRemotePort

func (s *ChatService) SetRemotePort(port int) error

SetRemotePort persists the port and restarts the listener if it is running (browser clients reconnect within ~1s via custom.js).

func (*ChatService) SetRemotePublicURL

func (s *ChatService) SetRemotePublicURL(url string) error

SetRemotePublicURL persists the optional public reverse-proxy base used for pairing links/QR (empty = LAN addresses only). No validation beyond trimming: the origin must simply be the one the phone will use.

func (*ChatService) SetSessionConfigOption

func (s *ChatService) SetSessionConfigOption(sessionID, configId, value string) error

SetSessionConfigOption 切换 session 的某个 config option(model/mode/effort),热切、即时生效。 懒 spawn:只读态(未活跃)下切换视为「继续会话」触发 spawn,spawn 完成后应用用户选的配置 (语义统一:切换 = 先 spawn 再应用,与发消息触发 spawn 一致)。已活跃则直接热切。

func (*ChatService) SetSessionPinned

func (s *ChatService) SetSessionPinned(sessionID string, pinned bool) error

SetSessionPinned 设置会话置顶(0008)。前端侧栏右键菜单切换 → 乐观本地重排即时生效; 持久化在 DB,pinned 由 ListSessions ORDER BY 接管顶部位置。

func (*ChatService) SetSessionWindowOnTop

func (s *ChatService) SetSessionWindowOnTop(sessionID string, onTop bool) error

SetSessionWindowOnTop 设置 popout 窗口的「始终置顶」状态(类似 VS Code 的置顶)。 macOS = NSWindow level floating;Windows = HWND_TOPMOST;Linux = keep_above。 前端维护 onTop state(toggle 按钮),调此 binding 应用到窗口。

func (*ChatService) ShrinkSessionWindow

func (s *ChatService) ShrinkSessionWindow(sessionID string)

ShrinkSessionWindow 缩窄 popout 窗口(右侧面板收起时调)。

func (*ChatService) StopSession

func (s *ChatService) StopSession(sessionID string) error

StopSession 取消正在进行的 Prompt(用户点「停止」):发干净 session/cancel(非杀进程), harness 与连接保持可用。runPrompt 在 Prompt 返回后推 idle/cancelled,前端据此切回可发送态。 It also records the one-shot stop intent (#126A): the drain right after that turn's idle consumes it and skips auto-continue (queue kept) — Stop must mean "stop", not "skip one item and keep going".

func (*ChatService) ToggleMaximise

func (s *ChatService) ToggleMaximise()

ToggleMaximise 双击顶部标题栏时切换窗口最大化/还原(非 fullscreen)。 单窗口桌面应用,取首个窗口。

func (*ChatService) UpdateMcpServer

func (s *ChatService) UpdateMcpServer(m store.McpServer) error

UpdateMcpServer 全量更新一个 MCP server(按 id;name 不可改)。

func (*ChatService) UpdatePermissionRule

func (s *ChatService) UpdatePermissionRule(rule store.PermissionRule) error

UpdatePermissionRule 更新一条权限规则,并刷新所有活跃 session 的规则快照。

func (*ChatService) UpdateProject

func (s *ChatService) UpdateProject(id, name, model string) error

UpdateProject 更新项目 name/model。

func (*ChatService) UpdateSessionCustomTitle

func (s *ChatService) UpdateSessionCustomTitle(sessionID, customTitle string) error

UpdateSessionCustomTitle sets a user-defined rename (0016), kept separate from the auto/harness-generated title. Empty customTitle clears it (sidebar falls back to Title). Rename is not content activity, so it does not touch updated_at (see store method).

func (*ChatService) UpdateSessionTags

func (s *ChatService) UpdateSessionTags(sessionID string, tags []string) ([]string, error)

UpdateSessionTags replaces a session's tag set (0021 / #150 MVP). The store layer normalizes the input (trim, drop empties, dedupe, cap 5); an empty result clears all tags. Returns the normalized set actually persisted so the frontend's optimistic update mirrors the DB instead of drifting (e.g. cap truncation). Tag edits are not content activity → updated_at untouched.

func (*ChatService) UpdateUserHarness

func (s *ChatService) UpdateUserHarness(id, name, command string) ([]harness.Harness, error)

UpdateUserHarness 改一个用户自添加 harness 的 name + command(id 不变:session 钉在 id 上, 改 id 会断开既有 session 关联)。内置 harness 不可改(IsBuiltin → 拒绝)。name 可空(兜底 id)。 改 command 后应重新 ProbeNewHarness 验证(前端编辑弹窗提供自检按钮)。 返回更新后的全量 harness 列表。

func (*ChatService) UpgradeHarness

func (s *ChatService) UpgradeHarness(id string) ([]harness.Harness, error)

UpgradeHarness 触发某 harness 的升级(委托给 Registry 配置的 Upgrader,通常是官方安装脚本)。 升级后自动重新发现并刷新缓存,返回最新列表(让前端能看到新版本号)。 升级报错时仍刷新一次并把错误塞进对应 harness 的 UpgradeError 字段,便于前端展示。

func (*ChatService) WorktreeGuests

func (s *ChatService) WorktreeGuests(sessionID string) ([]store.Session, error)

WorktreeGuests returns the guest sessions sharing the owner's worktree (same worktreePath, excluding the owner). Powers the owner-delete 3-option dialog ("N chats still use this worktree"). Non-owner (no worktreePath) → empty.

func (*ChatService) WorktreeKind

func (s *ChatService) WorktreeKind(sessionID string) (string, error)

WorktreeKind returns the session's worktree role: "project" (uses project dir, no worktree) / "owner" (created the worktree) / "guest" (entered an existing worktree). The frontend drives the delete flow + disables merge for guests off this.

type FilesDroppedPayload

type FilesDroppedPayload struct {
	Files     []string `json:"files"`     // absolute paths dropped from the OS file manager
	SessionID string   `json:"sessionId"` // data-md-session of the drop target element ("" if absent)
}

FilesDroppedPayload is the chat:files-dropped event payload.

type McpImportResult

type McpImportResult struct {
	Added    []string `json:"added"`    // 成功新增进 catalog 的 server 名
	Skipped  []string `json:"skipped"`  // 已存在(name 重复)跳过的
	Warnings []string `json:"warnings"` // 字段丢失 / 可能失败的告警(per-server)
	Errors   []string `json:"errors"`   // 完全无法解析的(per-server)
}

McpImportResult 一次 MCP 导入的结果汇总(前端人话呈现,§4.4)。

type PopoutPayload

type PopoutPayload struct {
	SessionID string `json:"sessionId"`
	Popped    bool   `json:"popped"` // true=已弹出到独立窗口;false=已收回
}

PopoutPayload 推给前端的 popout 状态。

type QueueItem

type QueueItem struct {
	ID          string           `json:"id"`
	Text        string           `json:"text"`
	Attachments []acp.Attachment `json:"attachments,omitempty"`
	ScheduledAt int64            `json:"scheduledAt"` // epoch ms; due when <= now
	// Recurring send (#111): RepeatEveryMs > 0 re-arms the item after each
	// successful send; SentCount counts those sends ("sent N" badge).
	RepeatEveryMs int64 `json:"repeatEveryMs"`
	SentCount     int64 `json:"sentCount"`
}

QueueItem is the wire shape of one queued message (chat:queue event + bindings). Attachments is the prompt-attachment array exactly as SendMessage takes it — built once at enqueue time, reused verbatim by drain and by InterruptAndSend ("send now"), so mention/image/audio blocks survive the queue round-trip.

type QueuePayload

type QueuePayload struct {
	SessionID string      `json:"sessionId"`
	Items     []QueueItem `json:"items"`
}

QueuePayload is the chat:queue event body: a full per-session snapshot. Emitted on every mutation, every drain-dequeue, and on OpenSession (initial state for a freshly attaching window).

type RemoteInfo

type RemoteInfo struct {
	Enabled   bool // persisted preference
	Running   bool // listener currently up
	Port      int
	Token     string
	URLs      []string // tokenless base URLs, one per LAN IPv4 address
	PublicURL string   // optional public reverse-proxy base (https://md.example.com)
	Attached  bool     // false when not wired (server-tag build / tests)
}

RemoteInfo is the settings-UI view of the embedded remote server.

type RemoteSessionInfo

type RemoteSessionInfo struct {
	ID        string
	Label     string
	CreatedAt string
	LastSeen  string
}

RemoteSessionInfo is one paired remote device for the settings UI. (No json tags — matches RemoteInfo's wire convention: Wails marshals Go field names, and the generated bindings + pane code agree on PascalCase.)

type SessionMetaPayload

type SessionMetaPayload struct {
	SessionID string `json:"sessionId"`
	Title     string `json:"title"`
}

SessionMetaPayload 会话元信息更新(标题等)。

type StatusPayload

type StatusPayload struct {
	SessionID string `json:"sessionId"`
	Status    string `json:"status"` // started | prompting | idle | error | closed | readonly | notice
	// Code 是稳定的机器错误码;前端按 code 经 i18n 翻译成人话提示(§4.4)。
	// error 与 notice 状态填(error:断连等真错误;notice:空 turn 等非异常温和提示,见 chat.notice.*)。
	Code   string `json:"code,omitempty"`
	Detail string `json:"detail,omitempty"`
	// RootCause: human-readable root cause extracted from the Prompt error
	// (e.g. the provider's quota text); set on error status when diagnostics
	// are attached (#46). The frontend i18n copy may interpolate it; never
	// surface raw protocol JSON (§4.4).
	RootCause string `json:"rootCause,omitempty"`
	// ResetAt: verbatim provider-side reset moment on quota exhaustion
	// (provider local time, e.g. "2026-08-26 16:32:32"); carried with
	// ErrCodeProviderQuotaExhausted (#46).
	ResetAt string `json:"resetAt,omitempty"`
	// Attempts: total Prompt attempts for this turn (1 + auto-retries, capped
	// by promptRetryLimit); set on error status when diagnostics are
	// attached (#46).
	Attempts int `json:"attempts,omitempty"`
}

StatusPayload 会话状态变更。

Jump to

Keyboard shortcuts

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