Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5873 fix(channels): improve /new and /issue feedback (#6578)
YYClaw2a19f9ba2c32
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.mdx b/apps/docs/content/docs/dingtalk-bot-integration.mdxindex d97f61cd8c..492cb6d061 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.mdx@@ -75,7 +75,7 @@ Setting this up for **multiple agents**? Repeat the whole flow once per agent| **@-mention in a group** | Add the bot to the group and @-mention it. Only the mentioning message is read — the bot does not listen to the whole group. || **Send images** | Images in a DM, or sent alongside a group @-mention, land in the conversation for the agent to see — PNG, JPEG, GIF, WebP, or BMP, up to 4 images per message and 10 MB each. Each image is copied into Multica storage, so it stays visible in the chat after DingTalk's temporary link expires. Images sent with `/issue` go to the created issue instead of the chat turn. Files and voice messages aren't supported. || **`/issue` command** | Starting a message with `/issue <title>` creates a Multica issue directly from your input, attributed to you, and posts the issue ID and title back into the same conversation. Put the description on following lines. Images sent in the same DingTalk message are attached to the created issue. The command itself does not appear in Multica Chat; the created issue is the result recorded in Multica. |-| **`/new` command** | Starting a message with `/new <your message>` runs that message without prior conversation context. Sending `/new` by itself records the same fresh-start intent for your next non-empty message without creating an empty turn. The conversation history remains intact. |+| **`/new` command** | Starting a message with `/new <your message>` runs that message without prior conversation context. Sending `/new` by itself records the same fresh-start intent for your next non-empty message without creating an empty turn, and the bot confirms when that intent is ready. The pending intent remains active until a later chat task is successfully queued. The conversation history remains intact. || **Reply** | The agent's answer is posted back into the same 1:1 chat or group. |## Use the bot (members)@@ -94,7 +94,7 @@ Only **members of the workspace** can use the bot. If you aren't a member, or yo- **In a 1:1 chat** — open the bot and message it directly; no mention needed, every message is read.- **Send images** — send screenshots or photos, with or without text; they show up in the conversation for the agent to work with. PNG, JPEG, GIF, WebP, or BMP; up to 4 images per message, 10 MB each.- **File an issue** — send `/issue the login redirect is broken on Safari`; add the description on following lines if needed. Multica creates the issue synchronously, attaches images from that message to it, and posts its ID and title back into the chat.-- **Start fresh** — send `/new <your message>` to run that message without prior context, or send `/new` by itself to apply the fresh start to your next non-empty message. Neither form removes the existing conversation history.+- **Start fresh** — send `/new <your message>` to run that message without prior context, or send `/new` by itself to apply the fresh start to your next non-empty message. A bare `/new` gets a confirmation, and its pending intent remains active until a later chat task is successfully queued. Neither form removes the existing conversation history.## Manage and disconnectdiff --git a/apps/docs/content/docs/lark-bot-integration.mdx b/apps/docs/content/docs/lark-bot-integration.mdxindex 0200305723..9cec12dd70 100644--- a/apps/docs/content/docs/lark-bot-integration.mdx+++ b/apps/docs/content/docs/lark-bot-integration.mdx@@ -54,7 +54,7 @@ Send:Safari stays on the login page after a successful sign-in.```-The first line becomes the title and the rest becomes the description. If you send `/issue` alone, Multica tries to use your previous message as the title.+The first line becomes the title and the rest becomes the description. Sending `/issue` alone creates nothing; the Bot replies with the required format instead.## Manage connectionsdiff --git a/apps/docs/content/docs/lark-bot-integration.zh.mdx b/apps/docs/content/docs/lark-bot-integration.zh.mdxindex 65398da04d..40458304a7 100644--- a/apps/docs/content/docs/lark-bot-integration.zh.mdx+++ b/apps/docs/content/docs/lark-bot-integration.zh.mdx@@ -54,7 +54,7 @@ import { Callout } from "fumadocs-ui/components/callout";Safari 登录成功后仍然停留在登录页。```-第一行成为标题,后面的内容成为描述。只发送 `/issue` 时,Multica 会尝试使用上一条消息作为标题。+第一行作为标题,其余内容作为描述。只发送 `/issue` 不会创建任务;Bot 会回复用法提示。## 管理连接diff --git a/server/internal/handler/channel_new_e2e_test.go b/server/internal/handler/channel_new_e2e_test.goindex 4c603adf60..478501d257 100644--- a/server/internal/handler/channel_new_e2e_test.go+++ b/server/internal/handler/channel_new_e2e_test.go@@ -31,6 +31,7 @@ func TestChannelNewCommandE2EStartsFreshProviderSession(t *testing.T) {text stringcommandText stringforceFresh bool+ followUpText stringwantStoredText stringwantForceFresh boolwantPriorSession string@@ -45,6 +46,15 @@ func TestChannelNewCommandE2EStartsFreshProviderSession(t *testing.T) {wantPriorSession: "old-provider-session",wantPriorWorkDir: "/tmp/old-provider-workdir",},+ {+ name: "bare /new applies to the next real message",+ channelType: channel.Type("slack"),+ text: "/new",+ commandText: "/new",+ followUpText: "what model are you?",+ wantStoredText: "what model are you?",+ wantForceFresh: true,+ },{name: "Slack /new message starts without provider context",channelType: channel.Type("slack"),@@ -91,12 +101,12 @@ func TestChannelNewCommandE2EStartsFreshProviderSession(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- runChannelNewCommandE2E(t, tt.channelType, tt.text, tt.commandText, tt.forceFresh, tt.wantStoredText, tt.wantForceFresh, tt.wantPriorSession, tt.wantPriorWorkDir)+ runChannelNewCommandE2E(t, tt.channelType, tt.text, tt.commandText, tt.forceFresh, tt.followUpText, tt.wantStoredText, tt.wantForceFresh, tt.wantPriorSession, tt.wantPriorWorkDir)})}}-func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, commandText string, adapterForceFresh bool, wantStoredText string, wantForceFresh bool, wantPriorSession, wantPriorWorkDir string) {+func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, commandText string, adapterForceFresh bool, followUpText, wantStoredText string, wantForceFresh bool, wantPriorSession, wantPriorWorkDir string) {t.Helper()ctx := context.Background()@@ -187,6 +197,38 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, comma}); err != nil {t.Fatalf("route channel message: %v", err)}+ if followUpText != "" {+ var taskCount, userMessageCount int+ var pendingFresh bool+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id = $1`, sessionID).Scan(&taskCount); err != nil {+ t.Fatalf("count tasks after bare /new: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM chat_message WHERE chat_session_id = $1 AND role = 'user'`, sessionID).Scan(&userMessageCount); err != nil {+ t.Fatalf("count messages after bare /new: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT pending_fresh FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID).Scan(&pendingFresh); err != nil {+ t.Fatalf("load pending fresh after bare /new: %v", err)+ }+ if taskCount != 0 || userMessageCount != 0 || !pendingFresh {+ t.Fatalf("bare /new state: tasks=%d messages=%d pending_fresh=%t, want 0/0/true", taskCount, userMessageCount, pendingFresh)+ }++ if err := router.Handle(ctx, channel.InboundMessage{+ EventID: "event-follow-up-" + t.Name(),+ MessageID: "message-follow-up-" + t.Name(),+ Type: channel.MsgTypeText,+ Text: followUpText,+ CommandText: followUpText,+ Source: channel.Source{+ ChannelType: channelType,+ ChatID: t.Name(),+ ChatType: channel.ChatTypeP2P,+ SenderID: "platform-user-e2e",+ },+ }); err != nil {+ t.Fatalf("route follow-up channel message: %v", err)+ }+ }var taskID stringvar forceFresh bool@@ -202,6 +244,13 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, commaif forceFresh != wantForceFresh {t.Fatalf("queued task %s: force_fresh_session = %t, want %t", taskID, forceFresh, wantForceFresh)}+ var pendingFresh bool+ if err := testPool.QueryRow(ctx, `SELECT pending_fresh FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID).Scan(&pendingFresh); err != nil {+ t.Fatalf("load pending fresh after task enqueue: %v", err)+ }+ if pendingFresh {+ t.Fatal("successful task enqueue did not consume pending_fresh")+ }var issueCount intif err := testPool.QueryRow(ctx, `@@ -306,6 +355,10 @@ func (b *channelNewE2ESessionBinder) EnsureSession(ctx context.Context, p engine})}+func (b *channelNewE2ESessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {+ return b.session.MarkPendingFresh(ctx, sessionID)+}+func (b *channelNewE2ESessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {return b.session.AppendUserMessage(ctx, engine.AppendInput{SessionID: p.SessionID,@@ -317,6 +370,7 @@ func (b *channelNewE2ESessionBinder) AppendMessage(ctx context.Context, p engineThreadID: p.Message.Source.ThreadID,ClaimToken: p.ClaimToken,MediaPendingSeconds: p.MediaPendingSeconds,+ ForceFresh: p.Message.ForceFresh,})}diff --git a/server/internal/integrations/channel/engine/issue_command.go b/server/internal/integrations/channel/engine/issue_command.goindex 647f9e6ae8..ee454ce781 100644--- a/server/internal/integrations/channel/engine/issue_command.go+++ b/server/internal/integrations/channel/engine/issue_command.go@@ -16,8 +16,7 @@ const issueCommandPrefix = "/issue"// - `/issue <title>` → Title = "<title>", Description = ""// - `/issue <title>\n<rest...>` → Title = "<title>", Description = "<rest>"// - `/issue` (alone, no title) → Title = "", Description = ""-// (the caller falls back to the previous user message; the parser does not-// do that lookup itself because it has no DB access)+// (the Router returns a usage result; it never infers a title from history)//// Only the first non-empty line is considered: a body that begins with blank// lines and then `/issue ...` still qualifies. A body whose first non-empty@@ -149,19 +148,3 @@ func matchingLineBounds(body, expected string) []textLineBounds {}return bounds}--// titleFromPreviousMessage derives a title from a prior chat message, used for-// the bare `/issue` fallback. The previous message may itself be an `/issue …`-// invocation (two commands in a row), in which case stripping the prefix yields-// the real intent; otherwise the first non-empty line is the title.-func titleFromPreviousMessage(body string) string {- if cmd, ok := ParseIssueCommand(body); ok {- return cmd.Title- }- for _, line := range strings.Split(body, "\n") {- if t := strings.TrimSpace(line); t != "" {- return t- }- }- return ""-}diff --git a/server/internal/integrations/channel/engine/issue_command_test.go b/server/internal/integrations/channel/engine/issue_command_test.goindex 1ea70cc4af..7bce204a5c 100644--- a/server/internal/integrations/channel/engine/issue_command_test.go+++ b/server/internal/integrations/channel/engine/issue_command_test.go@@ -41,18 +41,6 @@ func TestParseIssueCommand(t *testing.T) {}}-func TestTitleFromPreviousMessage(t *testing.T) {- if got := titleFromPreviousMessage("/issue Real title"); got != "Real title" {- t.Errorf("prev /issue should strip prefix: %q", got)- }- if got := titleFromPreviousMessage("\n first line\nsecond"); got != "first line" {- t.Errorf("prev plain should take first non-empty line: %q", got)- }- if got := titleFromPreviousMessage(" \n "); got != "" {- t.Errorf("blank prev → empty: %q", got)- }-}-func TestIssueDescriptionFromCommandBodyPreservesInlineLayout(t *testing.T) {body := "/issue explain below questions\nWhat is this?\n[Image]\nAnd what is this?\n[Image]"want := "What is this?\n[Image]\nAnd what is this?\n[Image]"diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.goindex 4265fbbaea..e2bade266c 100644--- a/server/internal/integrations/channel/engine/resolvers.go+++ b/server/internal/integrations/channel/engine/resolvers.go@@ -26,6 +26,8 @@ const (OutcomeDropped Outcome = "dropped"OutcomeNeedsBinding Outcome = "needs_binding"OutcomeIngested Outcome = "ingested"+ OutcomeFreshPending Outcome = "fresh_pending"+ OutcomeIssueUsage Outcome = "issue_usage"OutcomeAgentOffline Outcome = "agent_offline"OutcomeAgentArchived Outcome = "agent_archived")@@ -62,6 +64,10 @@ type Result struct {// because the shared duplicate guard found the active IssueID above.// Repliers render this as a business conflict, never as an internal error.IssueDuplicate bool+ // IssueUsageHadMedia marks a title-less /issue whose current inbound+ // message also carried downloadable media. Repliers use it to tell the+ // sender to include that media again with the corrected command.+ IssueUsageHadMedia bool// runScheduled reports whether this ingest scheduled a normal chat run.// It is Router-internal state: repliers must continue to use Outcome.runScheduled bool@@ -195,6 +201,7 @@ type Deduper interface {// rotated mid-flight.type SessionBinder interface {EnsureSession(ctx context.Context, p EnsureSessionParams) (pgtype.UUID, error)+ MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) errorAppendMessage(ctx context.Context, p AppendParams) (AppendResult, error)BindMedia(ctx context.Context, p BindMediaParams) error}diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex afedd8ef92..96053cccdf 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -54,9 +54,6 @@ type Router struct {stopping boollogger *slog.Logger-- pendingFreshMu sync.Mutex- pendingFresh map[string]time.Time}// Config tunes the Router. Zero values default.@@ -108,7 +105,6 @@ func NewRouter(issues IssueCreator, tasks TaskEnqueuer, reader SessionReader, cfmediaCancel: mediaCancel,mediaSem: make(chan struct{}, cfg.MediaConcurrency),logger: cfg.Logger,- pendingFresh: make(map[string]time.Time),mediaQueues: make(map[string]*mediaQueueEntry),}}@@ -346,9 +342,11 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// ForceFresh is a task-dispatch property. A bare command has no useful// task to dispatch, so remember the intent and apply it to the next real// message instead of writing or running an empty turn.- r.markPendingFresh(keyForSession(sessionID))+ if err := set.Session.MarkPendingFresh(ctx, sessionID); err != nil {+ return Result{}, finalizeRelease, fmt.Errorf("persist fresh command: %w", err)+ }return Result{- Outcome: OutcomeIngested,+ Outcome: OutcomeFreshPending,InstallationID: inst.ID,ChatSessionID: sessionID,Sender: msg.Source.SenderID,@@ -361,7 +359,14 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// duration — the append transaction anchors it to the DB clock, the same// clock every now()-based reader uses.mediaPendingSeconds := 0.0- resolveMedia := set.Media != nil && set.Media.HasMedia(msg)+ // AppendMessage must classify this exact CommandText again when it marks the+ // durable message as a channel command. Platform binders must preserve the+ // source carried in AppendParams.Message; changing it would let the media+ // decision here disagree with the terminal outcome after the append.+ parsedCommand, _ := ParseIssueCommand(msg.CommandText)+ issueNeedsUsage := parsedCommand != nil && parsedCommand.Title == ""+ hasMedia := set.Media != nil && set.Media.HasMedia(msg)+ resolveMedia := !issueNeedsUsage && hasMedia// The local monotonic budget starts BEFORE the append: the DB anchors its// fallback at now() during the insert, so a post-commit local start would// end Δ(append latency) AFTER the durable deadline — a window where the@@ -407,6 +412,11 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// 7. /issue command, if present. chat_message is already durable; all// error returns from here signal finalizeNone (or the defensive Mark).if appendRes.IssueCommand != nil {+ if appendRes.IssueCommand.Title == "" {+ res.Outcome = OutcomeIssueUsage+ res.IssueUsageHadMedia = hasMedia+ return res, postAppendFinalize, nil+ }if resolveMedia {// CommandText intentionally omits adapter-generated media placeholders so// image-before-command layouts still classify as /issue. Restore the@@ -638,17 +648,18 @@ func (r *Router) finishMediaQueue(key string, done chan struct{}) {// scheduleRun hands the per-session run trigger to the debouncer (or fires it// inline when batching is disabled).func (r *Router) scheduleRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID) {- key := keyForSession(sessionID)fresh := msg.ForceFreshif r.batcher == nil {- r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, r.takePendingFresh(key, fresh))+ r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, fresh)return}- if fresh {- r.markPendingFresh(key)- }+ key := keyForSession(sessionID)flush := func() {- r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, r.takePendingFresh(key, fresh))+ // A later message may replace this closure inside the debounce window.+ // AppendMessage persists ForceFresh on the channel binding, and+ // EnqueueChatTask consumes it transactionally, so correctness does not+ // depend on which message's in-memory closure wins.+ r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, fresh)}r.batcher.Schedule(key, flush)}@@ -666,21 +677,12 @@ func (r *Router) flushChatRun(set ResolverSet, inst ResolvedInstallation, msg chsession, err := r.reader.GetChatSession(ctx, sessionID)if err != nil {- if forceFresh {- r.markPendingFresh(keyForSession(sessionID))- }r.logger.Error("channel router: flush reload chat session failed","chat_session_id", uuidString(sessionID), "err", err.Error())r.clearTyping(ctx, set, sessionID)return}if _, err := r.tasks.EnqueueChatTask(ctx, session, initiatorUserID, forceFresh); err != nil {- if forceFresh {- // ForceFresh belongs to the first successfully queued run, not the- // first attempt. Preserve it across offline, archived, or transient- // enqueue failures so the next real message cannot resume old context.- r.markPendingFresh(keyForSession(sessionID))- }// No task was enqueued, so no task lifecycle event will ever publish and// the platform's bus-driven typing clear can never fire. Clear the// indicator here (before any notice) so the "processing" reaction does@@ -707,32 +709,6 @@ func (r *Router) clearTyping(ctx context.Context, set ResolverSet, sessionID pgt}}-func (r *Router) markPendingFresh(key string) {- r.pendingFreshMu.Lock()- defer r.pendingFreshMu.Unlock()- now := time.Now()- cutoff := now.Add(-pendingFreshTTL)- for pendingKey, markedAt := range r.pendingFresh {- if markedAt.Before(cutoff) {- delete(r.pendingFresh, pendingKey)- }- }- r.pendingFresh[key] = now-}--func (r *Router) takePendingFresh(key string, fallback bool) bool {- r.pendingFreshMu.Lock()- defer r.pendingFreshMu.Unlock()- markedAt, ok := r.pendingFresh[key]- delete(r.pendingFresh, key)- return fallback || (ok && time.Since(markedAt) <= pendingFreshTTL)-}--// Bare fresh intent is in-memory plumbing between the command and the next-// real message. Bound it so abandoned sessions cannot grow the Router map-// forever. A process restart has the same reset-loss boundary.-const pendingFreshTTL = 24 * time.Hour-// emitFlushReply delivers an offline/archived notice for a flushed run.func (r *Router) emitFlushReply(ctx context.Context, set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID, outcome Outcome) {if set.Replier == nil {@@ -837,8 +813,8 @@ func (r *Router) issuePrefix(ctx context.Context, workspaceID pgtype.UUID) strinreturn ws.IssuePrefix}-// ErrEmptyIssueTitle is returned by createIssue when /issue has no title and-// the binder's previous-message fallback found nothing usable.+// ErrEmptyIssueTitle is a defensive invariant error. Router handles a+// user-authored empty title as OutcomeIssueUsage before calling createIssue.var ErrEmptyIssueTitle = errors.New("issue title is empty")var _ channel.InboundHandler = (*Router)(nil).Handlediff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex cb659c6433..50ad9e73bf 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -80,12 +80,20 @@ type fakeBinder struct {lastEnsure EnsureSessionParamslastAppend AppendParamslastBind BindMediaParams+ pendingFresh int+ pendingErr error}func (f *fakeBinder) EnsureSession(_ context.Context, p EnsureSessionParams) (pgtype.UUID, error) {f.lastEnsure = preturn f.ensureID, f.ensureErr}+func (f *fakeBinder) MarkPendingFresh(_ context.Context, _ pgtype.UUID) error {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.pendingFresh+++ return f.pendingErr+}func (f *fakeBinder) AppendMessage(_ context.Context, p AppendParams) (AppendResult, error) {f.mu.Lock()delay := f.appendDelay@@ -120,6 +128,11 @@ func (f *fakeBinder) appendedParams() AppendParams {defer f.mu.Unlock()return f.lastAppend}+func (f *fakeBinder) pendingFreshCalls() int {+ f.mu.Lock()+ defer f.mu.Unlock()+ return f.pendingFresh+}type fakeAuditor struct {mu sync.Mutex@@ -922,6 +935,53 @@ func TestRouter_IssueCommand_InfrastructureFailureRemainsError(t *testing.T) {}}+func TestRouter_BareIssueReturnsUsageWithoutCreatingOrResolvingMedia(t *testing.T) {+ h := newHarness(t)+ h.binder.parseIssue = true+ msg := p2pMessage(t)+ msg.Text = "/issue"+ msg.CommandText = "/issue"+ msg.Type = channel.MsgTypeImage++ if err := h.router.Handle(context.Background(), msg); err != nil {+ t.Fatalf("bare issue must be a product outcome, got error: %v", err)+ }+ if h.issues.called {+ t.Fatal("bare issue unexpectedly called IssueService.Create")+ }+ if h.tasks.calls() != 0 {+ t.Fatalf("bare issue unexpectedly enqueued a chat task, calls=%d", h.tasks.calls())+ }+ if h.media.calls() != 0 {+ t.Fatalf("bare issue unexpectedly resolved media, calls=%d", h.media.calls())+ }+ if !waitFor(time.Second, func() bool {+ calls := h.replier.calls()+ return len(calls) == 1 && calls[0].Outcome == OutcomeIssueUsage && calls[0].IssueUsageHadMedia+ }) {+ t.Fatalf("issue usage result was not delivered: %+v", h.replier.calls())+ }+}++func TestRouter_BareIssueWithoutMediaDoesNotRequestMediaResend(t *testing.T) {+ h := newHarness(t)+ h.binder.parseIssue = true+ h.media.noMedia = true+ msg := p2pMessage(t)+ msg.Text = "/issue"+ msg.CommandText = "/issue"++ if err := h.router.Handle(context.Background(), msg); err != nil {+ t.Fatalf("bare issue must be a product outcome, got error: %v", err)+ }+ if !waitFor(time.Second, func() bool {+ calls := h.replier.calls()+ return len(calls) == 1 && calls[0].Outcome == OutcomeIssueUsage && !calls[0].IssueUsageHadMedia+ }) {+ t.Fatalf("plain issue usage result was not delivered: %+v", h.replier.calls())+ }+}+func TestRouter_IssueCommand_MediaTargetsCreatedIssue(t *testing.T) {for _, tc := range []struct {name string@@ -1287,7 +1347,7 @@ func TestRouter_AdapterFreshBodyIsNotParsedAgain(t *testing.T) {}}-func TestRouter_BareFreshSkipsEmptyTurnAndForcesNextRealMessage(t *testing.T) {+func TestRouter_BareFreshPersistsIntentAndRepliesWithoutEmptyTurn(t *testing.T) {h := newHarness(t)h.media.noMedia = true@@ -1308,24 +1368,14 @@ func TestRouter_BareFreshSkipsEmptyTurnAndForcesNextRealMessage(t *testing.T) {if h.dedup.marks() != 1 {t.Fatalf("bare fresh dedup marks = %d, want 1", h.dedup.marks())}-- next := p2pMessage(t)- next.MessageID = "om-2"- next.Text = "start the new topic"- if err := h.router.Handle(context.Background(), next); err != nil {- t.Fatalf("next Handle: %v", err)+ if h.binder.pendingFreshCalls() != 1 {+ t.Fatalf("pending fresh writes = %d, want 1", h.binder.pendingFreshCalls())}- if !h.tasks.freshArg() {- t.Fatal("the next real message must consume the pending ForceFresh intent")- }-- again := p2pMessage(t)- again.MessageID = "om-3"- if err := h.router.Handle(context.Background(), again); err != nil {- t.Fatalf("again Handle: %v", err)- }- if h.tasks.freshArg() {- t.Fatal("the pending ForceFresh intent must be consumed exactly once")+ if !waitFor(time.Second, func() bool {+ calls := h.replier.calls()+ return len(calls) == 1 && calls[0].Outcome == OutcomeFreshPending+ }) {+ t.Fatalf("fresh-pending result was not delivered: %+v", h.replier.calls())}}@@ -1346,38 +1396,23 @@ func TestRouter_AdapterBareFreshUsesOriginalCommandText(t *testing.T) {if h.tasks.wasCalled() {t.Fatal("adapter-enriched bare fresh must not schedule an empty agent run")}+ if h.binder.pendingFreshCalls() != 1 {+ t.Fatalf("pending fresh writes = %d, want 1", h.binder.pendingFreshCalls())+ }}-func TestRouter_BareFreshSurvivesFailedEnqueue(t *testing.T) {+func TestRouter_BareFreshPersistenceFailureDoesNotAcknowledge(t *testing.T) {h := newHarness(t)h.media.noMedia = true+ h.binder.pendingErr = errors.New("database unavailable")reset := p2pMessage(t)reset.Text = "/new"- if err := h.router.Handle(context.Background(), reset); err != nil {- t.Fatalf("bare fresh Handle: %v", err)- }-- h.tasks.err = service.ErrChatTaskAgentNoRuntime- failed := p2pMessage(t)- failed.MessageID = "om-2"- failed.Text = "first attempt while offline"- if err := h.router.Handle(context.Background(), failed); err != nil {- t.Fatalf("failed enqueue Handle: %v", err)+ if err := h.router.Handle(context.Background(), reset); err == nil {+ t.Fatal("bare fresh must fail when its durable intent cannot be stored")}- if !h.tasks.freshArg() {- t.Fatal("failed enqueue must still receive the pending ForceFresh intent")- }-- h.tasks.err = nil- next := p2pMessage(t)- next.MessageID = "om-3"- next.Text = "retry after runtime is available"- if err := h.router.Handle(context.Background(), next); err != nil {- t.Fatalf("retry Handle: %v", err)- }- if !h.tasks.freshArg() {- t.Fatal("pending ForceFresh intent must survive until a run queues")+ if len(h.replier.calls()) != 0 {+ t.Fatalf("failed persistence emitted a success reply: %+v", h.replier.calls())}}diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.goindex 90c82b56af..ab7a66a214 100644--- a/server/internal/integrations/channel/engine/session.go+++ b/server/internal/integrations/channel/engine/session.go@@ -55,7 +55,7 @@ type SessionQueries interface {LinkAttachmentsToChatMessage(ctx context.Context, arg db.LinkAttachmentsToChatMessageParams) ([]pgtype.UUID, error)ClaimChannelMediaPendingObjectsForBind(ctx context.Context, arg db.ClaimChannelMediaPendingObjectsForBindParams) ([]string, error)TouchChatSession(ctx context.Context, id pgtype.UUID) error- GetMostRecentUserChatMessage(ctx context.Context, chatSessionID pgtype.UUID) (db.ChatMessage, error)+ MarkChannelChatSessionPendingFresh(ctx context.Context, chatSessionID pgtype.UUID) (bool, error)UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg db.UpdateChannelChatSessionBindingReplyTargetParams) errorMarkChannelInboundDedupProcessed(ctx context.Context, arg db.MarkChannelInboundDedupProcessedParams) (int64, error)}@@ -107,8 +107,8 @@ func (a dbSessionQueries) ClaimChannelMediaPendingObjectsForBind(ctx context.Confunc (a dbSessionQueries) TouchChatSession(ctx context.Context, id pgtype.UUID) error {return a.q.TouchChatSession(ctx, id)}-func (a dbSessionQueries) GetMostRecentUserChatMessage(ctx context.Context, chatSessionID pgtype.UUID) (db.ChatMessage, error) {- return a.q.GetMostRecentUserChatMessage(ctx, chatSessionID)+func (a dbSessionQueries) MarkChannelChatSessionPendingFresh(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {+ return a.q.MarkChannelChatSessionPendingFresh(ctx, chatSessionID)}func (a dbSessionQueries) UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg db.UpdateChannelChatSessionBindingReplyTargetParams) error {return a.q.UpdateChannelChatSessionBindingReplyTarget(ctx, arg)@@ -283,6 +283,7 @@ type AppendInput struct {ThreadID stringClaimToken pgtype.UUIDMediaPendingSeconds float64+ ForceFresh bool}// BindMediaInput links already-uploaded media to either an /issue target or a@@ -322,21 +323,11 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Apdefer tx.Rollback(ctx)qtx := s.q.WithTx(tx)- // Parse before the insert so the bare-`/issue` previous-message fallback- // queries the message set that does NOT yet include this message.commandSource := in.CommandTextif commandSource == "" {commandSource = in.Body}cmd, _ := ParseIssueCommand(commandSource)- if cmd != nil && cmd.Title == "" {- prev, err := qtx.GetMostRecentUserChatMessage(ctx, in.SessionID)- if err == nil {- cmd.Title = titleFromPreviousMessage(prev.Content)- } else if !errors.Is(err, pgx.ErrNoRows) {- return AppendResult{}, fmt.Errorf("previous message lookup: %w", err)- }- }// channel_ingested is the immutable provenance the cancel path gates on:// it must be stamped in the same transaction as the message so no later@@ -355,6 +346,11 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Apif err := qtx.TouchChatSession(ctx, in.SessionID); err != nil {return AppendResult{}, fmt.Errorf("touch chat session: %w", err)}+ if in.ForceFresh {+ if _, err := qtx.MarkChannelChatSessionPendingFresh(ctx, in.SessionID); err != nil {+ return AppendResult{}, fmt.Errorf("mark pending fresh: %w", err)+ }+ }// Record the latest trigger so the decoupled outbound patcher can thread// its reply back into the originating topic.@@ -392,6 +388,15 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Apreturn AppendResult{MessageID: msg.ID, IssueCommand: cmd, DedupMarked: markedInTx}, nil}+// MarkPendingFresh persists a bare `/new` command. Non-bare `/new` messages+// mark the same flag inside AppendUserMessage's transaction instead.+func (s *ChatSession) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {+ if _, err := s.q.MarkChannelChatSessionPendingFresh(ctx, sessionID); err != nil {+ return fmt.Errorf("mark pending fresh: %w", err)+ }+ return nil+}+// BindMediaRefs creates attachment rows owned by IssueID when present, otherwise// links them to the existing durable chat message. It also clears the message's// media-pending marker. A failure rolls back the attachment rows, then clearsdiff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.goindex 2e03684393..1cb0dbca66 100644--- a/server/internal/integrations/channel/engine/session_test.go+++ b/server/internal/integrations/channel/engine/session_test.go@@ -58,9 +58,9 @@ type fakeSessionQueries struct {reconcilerOwnedKeys map[string]boolissueLookupErr error- prevMessage *string // GetMostRecentUserChatMessage result; nil → ErrNoRows- markRows int64 // MarkChannelInboundDedupProcessed result- createBindingErr error // simulate a unique violation on create+ markRows int64 // MarkChannelInboundDedupProcessed result+ pendingFresh bool+ createBindingErr error // simulate a unique violation on createraceWinner pgtype.UUID}@@ -159,11 +159,9 @@ func (f *fakeSessionQueries) TouchChatSession(context.Context, pgtype.UUID) erroreturn nil}-func (f *fakeSessionQueries) GetMostRecentUserChatMessage(context.Context, pgtype.UUID) (db.ChatMessage, error) {- if f.prevMessage != nil {- return db.ChatMessage{Content: *f.prevMessage}, nil- }- return db.ChatMessage{}, pgx.ErrNoRows+func (f *fakeSessionQueries) MarkChannelChatSessionPendingFresh(context.Context, pgtype.UUID) (bool, error) {+ f.pendingFresh = true+ return true, nil}func (f *fakeSessionQueries) UpdateChannelChatSessionBindingReplyTarget(context.Context, db.UpdateChannelChatSessionBindingReplyTargetParams) error {@@ -661,17 +659,39 @@ func TestBindMediaRefs_MissingIssueRollsBackAndClearsPendingMarker(t *testing.T)}}-func TestAppendUserMessage_BareIssueUsesPreviousMessage(t *testing.T) {+func TestAppendUserMessage_BareIssueKeepsTitleEmpty(t *testing.T) {f := newFake()- prev := "Make the export button work"- f.prevMessage = &prevs := newTestSession(f)res, err := s.AppendUserMessage(context.Background(), AppendInput{SessionID: uid(1), Body: "/issue", MessageID: "m2"})if err != nil {t.Fatalf("AppendUserMessage: %v", err)}- if res.IssueCommand == nil || res.IssueCommand.Title != "Make the export button work" {- t.Errorf("bare /issue should fall back to previous message title: %+v", res.IssueCommand)+ if res.IssueCommand == nil || res.IssueCommand.Title != "" {+ t.Errorf("bare /issue must remain titleless for the Router usage result: %+v", res.IssueCommand)+ }+}++func TestAppendUserMessage_FreshMessagePersistsPendingIntent(t *testing.T) {+ f := newFake()+ s := newTestSession(f)+ if _, err := s.AppendUserMessage(context.Background(), AppendInput{+ SessionID: uid(1), Body: "start over", MessageID: "m2", ForceFresh: true,+ }); err != nil {+ t.Fatalf("AppendUserMessage: %v", err)+ }+ if !f.pendingFresh {+ t.Fatal("fresh message did not persist pending intent in the append transaction")+ }+}++func TestMarkPendingFresh_BareCommandPersistsIntent(t *testing.T) {+ f := newFake()+ s := newTestSession(f)+ if err := s.MarkPendingFresh(context.Background(), uid(1)); err != nil {+ t.Fatalf("MarkPendingFresh: %v", err)+ }+ if !f.pendingFresh {+ t.Fatal("bare fresh command did not persist pending intent")}}diff --git a/server/internal/integrations/dingtalk/replier.go b/server/internal/integrations/dingtalk/replier.goindex 0c00fa61ad..fafbcfd83d 100644--- a/server/internal/integrations/dingtalk/replier.go+++ b/server/internal/integrations/dingtalk/replier.go@@ -26,12 +26,16 @@ import (// page. After they bind, their next message reaches the agent.// - AgentOffline / AgentArchived: a status notice so the user is not left// wondering why nothing happened.+// - FreshPending / IssueUsage: command confirmation or corrective guidance.// - Ingested with a synchronously-created /issue: a confirmation carrying the// issue identifier and title. Plain chat turns stay silent.const (- agentOfflineText = "⚠️ The agent is offline, so this message won't be processed automatically."- agentArchivedText = "⚠️ This agent has been archived and can't respond. Please contact your workspace admin."+ agentOfflineText = "⚠️ The agent is offline, so this message won't be processed automatically."+ agentArchivedText = "⚠️ This agent has been archived and can't respond. Please contact your workspace admin."+ freshPendingText = "✅ Fresh start ready. Your next chat message will run without previous context."+ issueUsageText = "Please include an issue title. Use:\n\n`/issue <title>`\n\n`[description]` (optional)"+ issueUsageWithMediaText = "Please add a title and resend with the image (*image can come before or after the command*):\n\n`/issue <title>`\n\n`[description]` (optional)"// Refusals for dropped /issue commands, carried over from the deleted// pre-engine IssueCommandProcessor: without them the user's command// vanishes with no signal that it will never be handled.@@ -57,7 +61,7 @@ type OutboundReplier struct {// OutboundReplierConfig configures the replier. Binding + AppURL are required for// the NeedsBinding prompt to work; without them the prompt is skipped (the-// offline/archived/issue notices still fire).+// status and command notices still fire).type OutboundReplierConfig struct {Binding bindingMinterDecrypt Decrypter@@ -119,6 +123,20 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstallr.logger.WarnContext(ctx, "dingtalk replier: archived notice failed","installation_id", util.UUIDToString(inst.ID), "error", err)}+ case engine.OutcomeFreshPending:+ if err := r.post(ctx, inst, msg, freshPendingText); err != nil {+ r.logger.WarnContext(ctx, "dingtalk replier: fresh-start confirmation failed",+ "installation_id", util.UUIDToString(inst.ID), "error", err)+ }+ case engine.OutcomeIssueUsage:+ text := issueUsageText+ if res.IssueUsageHadMedia {+ text = issueUsageWithMediaText+ }+ if err := r.post(ctx, inst, msg, text); err != nil {+ r.logger.WarnContext(ctx, "dingtalk replier: issue usage reply failed",+ "installation_id", util.UUIDToString(inst.ID), "error", err)+ }case engine.OutcomeIngested:if res.IssueID.Valid {text := issueCreatedText(res)diff --git a/server/internal/integrations/dingtalk/replier_test.go b/server/internal/integrations/dingtalk/replier_test.goindex eb39f903f0..08db8a0053 100644--- a/server/internal/integrations/dingtalk/replier_test.go+++ b/server/internal/integrations/dingtalk/replier_test.go@@ -29,6 +29,15 @@ func TestIssueDuplicateText(t *testing.T) {}}+func TestIssueUsageCopy(t *testing.T) {+ if issueUsageText != "Please include an issue title. Use:\n\n`/issue <title>`\n\n`[description]` (optional)" {+ t.Fatalf("plain issue usage copy = %q", issueUsageText)+ }+ if issueUsageWithMediaText != "Please add a title and resend with the image (*image can come before or after the command*):\n\n`/issue <title>`\n\n`[description]` (optional)" {+ t.Fatalf("media issue usage copy = %q", issueUsageWithMediaText)+ }+}+func TestDroppedReplyText(t *testing.T) {issueMsg := channel.InboundMessage{Text: "[Image]", CommandText: "/issue login is broken", AddressedToBot: true}cases := []struct {diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.goindex 8c5af1c448..222f5cb1f4 100644--- a/server/internal/integrations/dingtalk/resolvers.go+++ b/server/internal/integrations/dingtalk/resolvers.go@@ -231,6 +231,7 @@ func (r *deduper) Release(ctx context.Context, installationID pgtype.UUID, messatype chatSession interface {EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)+ MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) errorAppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error}@@ -250,6 +251,10 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio})}+func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {+ return r.session.MarkPendingFresh(ctx, sessionID)+}+func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {commandText := p.Message.CommandTextif commandText == "" {@@ -265,6 +270,7 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParamsThreadID: p.Message.Source.ThreadID,ClaimToken: p.ClaimToken,MediaPendingSeconds: p.MediaPendingSeconds,+ ForceFresh: p.Message.ForceFresh,})}diff --git a/server/internal/integrations/dingtalk/resolvers_test.go b/server/internal/integrations/dingtalk/resolvers_test.goindex 50dbcbe96c..e7ff20544a 100644--- a/server/internal/integrations/dingtalk/resolvers_test.go+++ b/server/internal/integrations/dingtalk/resolvers_test.go@@ -20,6 +20,7 @@ type captureChatSession struct {func (c *captureChatSession) EnsureSession(context.Context, engine.EnsureSessionInput) (pgtype.UUID, error) {return pgtype.UUID{}, nil}+func (c *captureChatSession) MarkPendingFresh(context.Context, pgtype.UUID) error { return nil }func (c *captureChatSession) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {c.append = inreturn engine.AppendResult{}, nil@@ -46,7 +47,7 @@ func TestSessionBinder_MapsCommandTextAndMediaDeadline(t *testing.T) {SessionID: session, Sender: sender, InstallationID: inst, ClaimToken: claim,MediaPendingSeconds: 45,Message: channel.InboundMessage{- MessageID: "m1", Text: "[Image]\n/issue fix login", CommandText: "/issue fix login",+ MessageID: "m1", Text: "[Image]\n/issue fix login", CommandText: "/issue fix login", ForceFresh: true,},})if err != nil {@@ -56,7 +57,7 @@ func TestSessionBinder_MapsCommandTextAndMediaDeadline(t *testing.T) {if in.Body != "[Image]\n/issue fix login" || in.CommandText != "/issue fix login" {t.Fatalf("body/command = %q/%q", in.Body, in.CommandText)}- if in.MediaPendingSeconds != 45 || in.SessionID != session || in.Sender != sender || in.InstallationID != inst || in.ClaimToken != claim {+ if in.MediaPendingSeconds != 45 || !in.ForceFresh || in.SessionID != session || in.Sender != sender || in.InstallationID != inst || in.ClaimToken != claim {t.Fatalf("mapped append input = %+v", in)}}diff --git a/server/internal/integrations/lark/doc.go b/server/internal/integrations/lark/doc.goindex 031309ead9..b72b42298d 100644--- a/server/internal/integrations/lark/doc.go+++ b/server/internal/integrations/lark/doc.go@@ -13,8 +13,9 @@// 5. Dispatcher (inbound pipeline: installation route → top-level// message_id dedup → group filter → identity check → ensure// session → append → /issue → enqueue chat task; typed outcomes-// for offline / archived; emit returns DispatchResult + error so-// the connector can post the matching Lark-side reply card)+// for offline / archived / command guidance; emit returns+// DispatchResult + error so the connector can post the matching+// Lark-side reply card)// 6. AuditLogger (lark_inbound_audit; deliberately no body column)// 7. APIClient interface + http_client.go (real Lark Open Platform// transport for IM v1 send/patch + binding prompt + bot info;@@ -35,7 +36,8 @@// 11. OutcomeReplier (outbound side of the EventEmitter contract:// NeedsBinding mints a token + sends the binding prompt;// AgentOffline / AgentArchived push status notice cards into the-// chat; Ingested is owned by the Patcher; Dropped is silent)+// chat; FreshPending / IssueUsage push command guidance; Ingested+// is owned by the Patcher; Dropped is silent)// 12. RegistrationService (RFC 8628 device-flow scan-to-install: opens// a session against accounts.feishu.cn, polls in the background,// and on success writes through InstallationService + auto-bindsdiff --git a/server/internal/integrations/lark/feishu_channel_test.go b/server/internal/integrations/lark/feishu_channel_test.goindex 0b0b18f513..6f075d7a95 100644--- a/server/internal/integrations/lark/feishu_channel_test.go+++ b/server/internal/integrations/lark/feishu_channel_test.go@@ -765,10 +765,11 @@ func TestChannelMsgType(t *testing.T) {func TestDispatchResultFromEngine(t *testing.T) {res := dispatchResultFromEngine(engine.Result{- Outcome: engine.OutcomeNeedsBinding,- Sender: "ou_user",- IssueIdentifier: "MUL-7",- IssueDuplicate: true,+ Outcome: engine.OutcomeNeedsBinding,+ Sender: "ou_user",+ IssueIdentifier: "MUL-7",+ IssueDuplicate: true,+ IssueUsageHadMedia: true,})if res.Outcome != OutcomeNeedsBinding {t.Fatalf("outcome not mapped: %q", res.Outcome)@@ -782,4 +783,7 @@ func TestDispatchResultFromEngine(t *testing.T) {if !res.IssueDuplicate {t.Fatal("issue duplicate flag not mapped")}+ if !res.IssueUsageHadMedia {+ t.Fatal("issue usage media flag not mapped")+ }}diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.goindex ef115c7c67..59e5ee4145 100644--- a/server/internal/integrations/lark/feishu_resolvers.go+++ b/server/internal/integrations/lark/feishu_resolvers.go@@ -159,6 +159,7 @@ func (r *feishuDeduper) Release(ctx context.Context, installationID pgtype.UUID,// unit-tested with a fake; *engine.ChatSession is the production value.type chatSession interface {EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)+ MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) errorAppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error}@@ -202,6 +203,10 @@ func (r *feishuSessionBinder) EnsureSession(ctx context.Context, p engine.Ensure})}+func (r *feishuSessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {+ return r.session.MarkPendingFresh(ctx, sessionID)+}+func (r *feishuSessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {commandText := p.Message.CommandTextif commandText == "" {@@ -217,6 +222,7 @@ func (r *feishuSessionBinder) AppendMessage(ctx context.Context, p engine.AppendThreadID: p.Message.Source.ThreadID,ClaimToken: p.ClaimToken,MediaPendingSeconds: p.MediaPendingSeconds,+ ForceFresh: p.Message.ForceFresh,})}@@ -269,16 +275,17 @@ func (r *feishuOutboundReplier) Reply(ctx context.Context, inst engine.ResolvedI// the OutcomeReplier consumes. The Outcome/DropReason string values match 1:1.func dispatchResultFromEngine(res engine.Result) DispatchResult {return DispatchResult{- Outcome: Outcome(string(res.Outcome)),- DropReason: DropReason(string(res.DropReason)),- InstallationID: res.InstallationID,- ChatSessionID: res.ChatSessionID,- SenderOpenID: OpenID(res.Sender),- IssueID: res.IssueID,- IssueNumber: res.IssueNumber,- IssueIdentifier: res.IssueIdentifier,- IssueTitle: res.IssueTitle,- IssueDuplicate: res.IssueDuplicate,+ Outcome: Outcome(string(res.Outcome)),+ DropReason: DropReason(string(res.DropReason)),+ InstallationID: res.InstallationID,+ ChatSessionID: res.ChatSessionID,+ SenderOpenID: OpenID(res.Sender),+ IssueID: res.IssueID,+ IssueNumber: res.IssueNumber,+ IssueIdentifier: res.IssueIdentifier,+ IssueTitle: res.IssueTitle,+ IssueDuplicate: res.IssueDuplicate,+ IssueUsageHadMedia: res.IssueUsageHadMedia,}}diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.goindex 5ccce649c1..50407c55ef 100644--- a/server/internal/integrations/lark/feishu_resolvers_test.go+++ b/server/internal/integrations/lark/feishu_resolvers_test.go@@ -31,6 +31,8 @@ func (f *fakeChatSession) EnsureSession(_ context.Context, in engine.EnsureSessireturn binderUUID(42), nil}+func (f *fakeChatSession) MarkPendingFresh(context.Context, pgtype.UUID) error { return nil }+func (f *fakeChatSession) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {f.appendIn = inreturn engine.AppendResult{}, nil@@ -137,6 +139,7 @@ func TestFeishuSessionBinder_AppendUsesUnenrichedCommandBody(t *testing.T) {MessageID: "om_1",Text: "> quoted context\n/issue Real intent",CommandText: "/issue Real intent",+ ForceFresh: true,Source: channel.Source{ChatID: "oc", ThreadID: "th_1"},},}); err != nil {@@ -150,7 +153,7 @@ func TestFeishuSessionBinder_AppendUsesUnenrichedCommandBody(t *testing.T) {if got.Body != "> quoted context\n/issue Real intent" {t.Errorf("Body must be the (enriched) Message.Text, got %q", got.Body)}- if got.MessageID != "om_1" || got.ThreadID != "th_1" || got.SessionID != binderUUID(1) ||+ if got.MessageID != "om_1" || got.ThreadID != "th_1" || !got.ForceFresh || got.SessionID != binderUUID(1) ||got.Sender != binderUUID(7) || got.InstallationID != binderUUID(2) || got.ClaimToken != binderUUID(9) {t.Errorf("append mapping wrong: %+v", got)}diff --git a/server/internal/integrations/lark/feishu_types.go b/server/internal/integrations/lark/feishu_types.goindex 8ed36f13a7..3d81f6e097 100644--- a/server/internal/integrations/lark/feishu_types.go+++ b/server/internal/integrations/lark/feishu_types.go@@ -72,6 +72,10 @@ const (OutcomeNeedsBinding Outcome = "needs_binding"// OutcomeIngested — the message landed and a run was (or will be) enqueued.OutcomeIngested Outcome = "ingested"+ // OutcomeFreshPending — a bare /new was persisted for the next chat turn.+ OutcomeFreshPending Outcome = "fresh_pending"+ // OutcomeIssueUsage — /issue was sent without its required title.+ OutcomeIssueUsage Outcome = "issue_usage"// OutcomeAgentOffline — landed, but the agent has no runtime bound.OutcomeAgentOffline Outcome = "agent_offline"// OutcomeAgentArchived — landed, but the agent is archived.@@ -98,4 +102,7 @@ type DispatchResult struct {// IssueDuplicate distinguishes an active-issue conflict from a successful// create while carrying the existing issue fields above.IssueDuplicate bool+ // IssueUsageHadMedia asks the usage reply to tell the sender to include the+ // current message's media again with the corrected command.+ IssueUsageHadMedia bool}diff --git a/server/internal/integrations/lark/outcome_replier.go b/server/internal/integrations/lark/outcome_replier.goindex 0d71858636..ff163df000 100644--- a/server/internal/integrations/lark/outcome_replier.go+++ b/server/internal/integrations/lark/outcome_replier.go@@ -17,15 +17,14 @@ import (// appropriate Lark-side reply card. This is the outbound half of the// `EventEmitter` contract in hub.go: NeedsBinding sends the binding// prompt to the sender's open_id, AgentOffline / AgentArchived send-// a status notice into the chat. OutcomeIngested is owned by the-// Patcher (task lifecycle); OutcomeDropped is silent.+// a status notice into the chat, and FreshPending / IssueUsage send+// command guidance. OutcomeIngested is owned by the Patcher (task+// lifecycle); OutcomeDropped is silent.//// Reply is best-effort by design: a transient Lark outage MUST NOT-// fail the inbound pipeline (the message is already durable in-// chat_session by the time we get here for OutcomeIngested, and for-// the other outcomes there is no durable side effect to undo). Errors-// are logged and swallowed; the next inbound message for the same-// user retries the reply on its own.+// fail the inbound pipeline. Any command state or chat message is already+// durable by the time we get here, so a reply failure cannot roll it back.+// Errors are logged and swallowed.type OutcomeReplier interface {Reply(ctx context.Context, inst Installation, msg InboundMessage, res DispatchResult)}@@ -53,7 +52,7 @@ type noopReplier struct {func (n *noopReplier) Reply(ctx context.Context, inst Installation, msg InboundMessage, res DispatchResult) {switch res.Outcome {- case OutcomeNeedsBinding, OutcomeAgentOffline, OutcomeAgentArchived:+ case OutcomeNeedsBinding, OutcomeAgentOffline, OutcomeAgentArchived, OutcomeFreshPending, OutcomeIssueUsage:n.log.Warn("lark outcome replier: outbound reply skipped (replier not wired)","outcome", string(res.Outcome),"installation_id", uuidString(inst.ID),@@ -180,6 +179,26 @@ func (r *LarkOutcomeReplier) Reply(ctx context.Context, inst Installation, msg I"err", err.Error(),)}+ case OutcomeFreshPending:+ if err := r.sendChatNotice(ctx, inst, msg, freshPendingCopy); err != nil {+ r.log.Warn("lark outcome replier: fresh-start confirmation failed",+ "installation_id", uuidString(inst.ID),+ "chat_id", string(msg.ChatID),+ "err", err.Error(),+ )+ }+ case OutcomeIssueUsage:+ copy := issueUsageCopy+ if res.IssueUsageHadMedia {+ copy = issueUsageWithMediaCopy+ }+ if err := r.sendChatNotice(ctx, inst, msg, copy); err != nil {+ r.log.Warn("lark outcome replier: issue usage reply failed",+ "installation_id", uuidString(inst.ID),+ "chat_id", string(msg.ChatID),+ "err", err.Error(),+ )+ }case OutcomeIngested:// The agent's chat reply itself goes through the Patcher. An /issue// command gets an immediate product result: either the newly created@@ -388,6 +407,9 @@ func renderNoticeCard(header, body string) (string, error) {// match the §4.6 design: an offline agent will run when the daemon// comes back; an archived agent needs operator action.const (- agentOfflineCopy = "Agent 当前离线,消息已记录。下次 daemon 上线后会自动继续处理。"- agentArchivedCopy = "这个 Agent 已被归档,无法继续处理消息。请联系工作区管理员恢复或重新绑定。"+ agentOfflineCopy = "Agent 当前离线,消息已记录。下次 daemon 上线后会自动继续处理。"+ agentArchivedCopy = "这个 Agent 已被归档,无法继续处理消息。请联系工作区管理员恢复或重新绑定。"+ freshPendingCopy = "✅ 已准备开始新对话。你的下一条聊天消息将不带之前的上下文运行。"+ issueUsageCopy = "请填写任务标题,格式如下:\n\n`/issue <标题>`\n`[描述]`(可选)"+ issueUsageWithMediaCopy = "请添加标题,并与图片或视频一起重新发送(*图片或视频可以位于命令之前或之后*):\n\n`/issue <标题>`\n`[描述]`(可选)")diff --git a/server/internal/integrations/lark/outcome_replier_test.go b/server/internal/integrations/lark/outcome_replier_test.goindex 5dbe254070..fc544a197a 100644--- a/server/internal/integrations/lark/outcome_replier_test.go+++ b/server/internal/integrations/lark/outcome_replier_test.go@@ -240,6 +240,35 @@ func TestLarkOutcomeReplierAgentArchivedSendsCard(t *testing.T) {}}+func TestLarkOutcomeReplierCommandOutcomesSendGuidance(t *testing.T) {+ for _, tc := range []struct {+ name string+ outcome Outcome+ hadMedia bool+ want string+ }{+ {"fresh pending", OutcomeFreshPending, false, "下一条聊天消息"},+ {"plain issue usage", OutcomeIssueUsage, false, "请填写任务标题"},+ {"issue usage with media", OutcomeIssueUsage, true, "请添加标题,并与图片或视频一起重新发送"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true}+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{+ APIClient: stub, BindingSvc: &BindingTokenService{}, Credentials: stubCredentialsResolver{secret: "s"},+ Queries: stubReplierQueries{}, AppURL: "https://multica.test", Logger: log,+ })+ rep.Reply(context.Background(), Installation{}, InboundMessage{ChatID: "oc_chat"}, DispatchResult{Outcome: tc.outcome, IssueUsageHadMedia: tc.hadMedia})+ if len(stub.interactiveOut) != 1 {+ t.Fatalf("expected one guidance card, got %d", len(stub.interactiveOut))+ }+ if !contains(stub.interactiveOut[0].CardJSON, tc.want) {+ t.Fatalf("guidance card %q does not contain %q", stub.interactiveOut[0].CardJSON, tc.want)+ }+ })+ }+}+// TestLarkOutcomeReplierIngestedAndDroppedAreSilent asserts that the// replier does NOT call the APIClient on outcomes owned elsewhere// (Patcher handles Ingested; Dropped is informational only).diff --git a/server/internal/integrations/slack/replier.go b/server/internal/integrations/slack/replier.goindex 391194dc1c..12c7567552 100644--- a/server/internal/integrations/slack/replier.go+++ b/server/internal/integrations/slack/replier.go@@ -33,6 +33,8 @@ import (const (agentOfflineText = "⚠️ The agent is offline right now. Your message was received and will be handled once it's back online."agentArchivedText = "⚠️ This agent has been archived and can't respond. Please contact your workspace admin."+ freshPendingText = "✅ Fresh start ready. Your next chat message will run without previous context."+ issueUsageText = "Please include an issue title. Use:\n\n`/issue <title>`\n`[description]` (optional)")// bindingMinter is the binding-token surface the replier needs.@@ -117,6 +119,16 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstallr.logger.WarnContext(ctx, "slack replier: archived notice failed","installation_id", util.UUIDToString(inst.ID), "error", err)}+ case engine.OutcomeFreshPending:+ if err := r.post(ctx, inst, msg, freshPendingText); err != nil {+ r.logger.WarnContext(ctx, "slack replier: fresh-start confirmation failed",+ "installation_id", util.UUIDToString(inst.ID), "error", err)+ }+ case engine.OutcomeIssueUsage:+ if err := r.post(ctx, inst, msg, issueUsageText); err != nil {+ r.logger.WarnContext(ctx, "slack replier: issue usage reply failed",+ "installation_id", util.UUIDToString(inst.ID), "error", err)+ }case engine.OutcomeIngested:// Only an /issue product result warrants an immediate reply; a plain// chat message stays silent (the agent's own reply lands via ChatDone).diff --git a/server/internal/integrations/slack/replier_test.go b/server/internal/integrations/slack/replier_test.goindex 965e88c08f..591c7ca68b 100644--- a/server/internal/integrations/slack/replier_test.go+++ b/server/internal/integrations/slack/replier_test.go@@ -125,6 +125,23 @@ func TestReply_AgentOfflineAndArchived_PostNotices(t *testing.T) {}}+func TestReply_CommandOutcomes_PostGuidance(t *testing.T) {+ for _, tc := range []struct {+ outcome engine.Outcome+ want string+ }{+ {engine.OutcomeFreshPending, freshPendingText},+ {engine.OutcomeIssueUsage, issueUsageText},+ } {+ sender := &fakeReplySender{}+ r := newTestReplier(&fakeBindingMinter{}, sender)+ r.Reply(context.Background(), testResolvedInstallation(t), testInboundForReply(), engine.Result{Outcome: tc.outcome})+ if sender.calls != 1 || sender.sent == nil || sender.sent.Text != tc.want {+ t.Errorf("outcome %s: got %d sends, text %q, want %q", tc.outcome, sender.calls, textOrEmpty(sender.sent), tc.want)+ }+ }+}+func TestReply_IngestedWithIssue_Confirms(t *testing.T) {sender := &fakeReplySender{}r := newTestReplier(&fakeBindingMinter{}, sender)diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.goindex bdec49848c..ef21ab7605 100644--- a/server/internal/integrations/slack/resolvers.go+++ b/server/internal/integrations/slack/resolvers.go@@ -332,6 +332,10 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio})}+func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {+ return r.session.MarkPendingFresh(ctx, sessionID)+}+func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {_, _, replyThread := slackSessionRouting(p.Message)commandText := p.Message.CommandText@@ -348,6 +352,7 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParamsThreadID: replyThread,ClaimToken: p.ClaimToken,MediaPendingSeconds: p.MediaPendingSeconds,+ ForceFresh: p.Message.ForceFresh,})}diff --git a/server/internal/integrations/wecom/replier.go b/server/internal/integrations/wecom/replier.goindex 552e5c487b..3eb5c98f52 100644--- a/server/internal/integrations/wecom/replier.go+++ b/server/internal/integrations/wecom/replier.go@@ -24,6 +24,8 @@ import (const (agentOfflineText = "⚠️ 智能体当前不在线,你的消息已收到,等它上线后会处理。"agentArchivedText = "⚠️ 该智能体已归档,无法回复。请联系工作区管理员。"+ freshPendingText = "✅ 已准备开始新对话。你的下一条聊天消息将不带之前的上下文运行。"+ issueUsageText = "请填写任务标题,格式如下:\n\n`/issue <标题>`\n`[描述]`(可选)")// OutboundReplier implements engine.OutboundReplier for WeCom.@@ -114,6 +116,16 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstallr.logger.WarnContext(ctx, "wecom replier: archived notice failed","installation_id", util.UUIDToString(inst.ID), "error", err)}+ case engine.OutcomeFreshPending:+ if err := r.post(ctx, inst, msg, freshPendingText); err != nil {+ r.logger.WarnContext(ctx, "wecom replier: fresh-start confirmation failed",+ "installation_id", util.UUIDToString(inst.ID), "error", err)+ }+ case engine.OutcomeIssueUsage:+ if err := r.post(ctx, inst, msg, issueUsageText); err != nil {+ r.logger.WarnContext(ctx, "wecom replier: issue usage reply failed",+ "installation_id", util.UUIDToString(inst.ID), "error", err)+ }case engine.OutcomeIngested:// Only a /issue-created message warrants a confirmation; a plain// chat message stays silent (the agent's own reply lands viadiff --git a/server/internal/integrations/wecom/replier_test.go b/server/internal/integrations/wecom/replier_test.goindex 65e7e9813b..6eafbd7441 100644--- a/server/internal/integrations/wecom/replier_test.go+++ b/server/internal/integrations/wecom/replier_test.go@@ -158,6 +158,27 @@ func TestPost_AddressesRoomChatID(t *testing.T) {}}+func TestReply_CommandOutcomes_PostGuidance(t *testing.T) {+ for _, tc := range []struct {+ outcome engine.Outcome+ want string+ }{+ {engine.OutcomeFreshPending, freshPendingText},+ {engine.OutcomeIssueUsage, issueUsageText},+ } {+ t.Run(string(tc.outcome), func(t *testing.T) {+ r, inst, conn := newReplierWithConn(t)+ msg := channel.InboundMessage{Source: channel.Source{ChatID: "USER_A", ChatType: channel.ChatTypeP2P, SenderID: "USER_A"}}+ r.Reply(context.Background(), inst, msg, engine.Result{Outcome: tc.outcome})+ body := conn.sendBody(t, 0)+ markdown, _ := body["markdown"].(map[string]any)+ if got, _ := markdown["content"].(string); got != tc.want {+ t.Fatalf("reply text = %q, want %q", got, tc.want)+ }+ })+ }+}+// TestSendBindingPrompt_GroupNeverLeaksToken drives the REAL sendBindingPrompt// group branch — the single line the whole #1 fix rests on. It asserts the// token-bearing frame goes only to the sender at chat_type=1, the group gets adiff --git a/server/internal/integrations/wecom/resolvers_test.go b/server/internal/integrations/wecom/resolvers_test.goindex 307feafe2f..394a07964f 100644--- a/server/internal/integrations/wecom/resolvers_test.go+++ b/server/internal/integrations/wecom/resolvers_test.go@@ -34,6 +34,7 @@ func (f *fakeSessionBinder) EnsureSession(_ context.Context, in engine.EnsureSesf.ensureIn = inreturn f.sessID, nil}+func (f *fakeSessionBinder) MarkPendingFresh(context.Context, pgtype.UUID) error { return nil }func (f *fakeSessionBinder) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {f.appendIn = inreturn engine.AppendResult{}, nil@@ -67,13 +68,13 @@ func TestSessionBinder_AppendUsesTextAsCommand(t *testing.T) {b := &sessionBinder{session: fb}_, err := b.AppendMessage(context.Background(), engine.AppendParams{SessionID: mustTestUUID(t),- Message: channel.InboundMessage{Text: "/issue do a thing", MessageID: "m9"},+ Message: channel.InboundMessage{Text: "/issue do a thing", MessageID: "m9", ForceFresh: true},})if err != nil {t.Fatalf("AppendMessage: %v", err)}- if fb.appendIn.Body != "/issue do a thing" || fb.appendIn.CommandText != "/issue do a thing" {- t.Errorf("append body/command = %q/%q, want both to equal the text (no adapter command source to prefer)", fb.appendIn.Body, fb.appendIn.CommandText)+ if fb.appendIn.Body != "/issue do a thing" || fb.appendIn.CommandText != "/issue do a thing" || !fb.appendIn.ForceFresh {+ t.Errorf("append body/command/forceFresh = %q/%q/%t, want text fallback preserved with fresh intent", fb.appendIn.Body, fb.appendIn.CommandText, fb.appendIn.ForceFresh)}}diff --git a/server/internal/integrations/wecom/wecom_resolvers.go b/server/internal/integrations/wecom/wecom_resolvers.goindex 1983827994..ac0173c719 100644--- a/server/internal/integrations/wecom/wecom_resolvers.go+++ b/server/internal/integrations/wecom/wecom_resolvers.go@@ -73,6 +73,7 @@ func NewResolverSet(// production value.type engineSessionBinder interface {EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)+ MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) errorAppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)}@@ -214,6 +215,10 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio})}+func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {+ return r.session.MarkPendingFresh(ctx, sessionID)+}+func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {// The adapter's own command source wins, and Text is only the fallback.// Overwriting it with Text — which this used to do — threw away the@@ -232,6 +237,7 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParamsCommandText: commandText,MessageID: p.Message.MessageID,ClaimToken: p.ClaimToken,+ ForceFresh: p.Message.ForceFresh,})}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex a5e2934cd9..cd50133e07 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1654,6 +1654,16 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSeif currentSession.Status != "active" {return db.AgentTaskQueue{}, ErrChatSessionArchived}+ // Lock the channel binding only after the chat_session lock above. The+ // append path touches chat_session before binding as well, so this order+ // avoids an ABBA edge while keeping pending fresh in the enqueue transaction.+ pendingFresh, err := qtx.LockChannelChatSessionPendingFresh(ctx, chatSession.ID)+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return db.AgentTaskQueue{}, fmt.Errorf("lock channel pending fresh: %w", err)+ }+ if err == nil && pendingFresh {+ forceFreshSession = true+ }mediaPendingUntil, err := qtx.GetChannelMediaPendingUntil(ctx, chatSession.ID)if err != nil && !errors.Is(err, pgx.ErrNoRows) {slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)@@ -1705,6 +1715,11 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSecase !errors.Is(err, pgx.ErrNoRows):return db.AgentTaskQueue{}, fmt.Errorf("defer chat task for sealed pending media: %w", err)}+ if pendingFresh {+ if err := qtx.ClearChannelChatSessionPendingFresh(ctx, chatSession.ID); err != nil {+ return db.AgentTaskQueue{}, fmt.Errorf("clear channel pending fresh: %w", err)+ }+ }if err := tx.Commit(ctx); err != nil {return db.AgentTaskQueue{}, fmt.Errorf("commit chat task enqueue: %w", err)}diff --git a/server/internal/service/task_channel_command_media_test.go b/server/internal/service/task_channel_command_media_test.goindex 34f9c73ba2..2c458a8478 100644--- a/server/internal/service/task_channel_command_media_test.go+++ b/server/internal/service/task_channel_command_media_test.go@@ -2,6 +2,7 @@ package serviceimport ("context"+ "errors""testing""time"@@ -28,11 +29,71 @@ func seedChannelCommandSession(t *testing.T, pool *pgxpool.Pool, workspaceID, agcleanupCtx := context.Background()_, _ = pool.Exec(cleanupCtx, `DELETE FROM agent_task_queue WHERE chat_session_id = $1`, chatSessionID)_, _ = pool.Exec(cleanupCtx, `DELETE FROM chat_message WHERE chat_session_id = $1`, chatSessionID)+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, chatSessionID)_, _ = pool.Exec(cleanupCtx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID)})return chatSessionID}+func TestEnqueueChatTaskConsumesPendingFreshOnlyOnSuccess(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)+ chatSessionID := seedChannelCommandSession(t, pool, workspaceID, agentID, userID)+ var runtimeID string+ if err := pool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {+ t.Fatalf("load agent runtime: %v", err)+ }++ if _, err := pool.Exec(ctx, `+ INSERT INTO channel_chat_session_binding (+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, pending_fresh+ ) VALUES ($1, gen_random_uuid(), 'dingtalk', 'chat-fresh', 'p2p', TRUE)`, chatSessionID); err != nil {+ t.Fatalf("seed channel binding: %v", err)+ }+ if _, err := pool.Exec(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content)+ VALUES ($1, 'user', 'start the new topic')`, chatSessionID); err != nil {+ t.Fatalf("seed chat message: %v", err)+ }++ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}+ session := db.ChatSession{ID: util.MustParseUUID(chatSessionID), AgentID: util.MustParseUUID(agentID)}+ initiator := util.MustParseUUID(userID)++ if _, err := pool.Exec(ctx, `UPDATE agent SET runtime_id = NULL WHERE id = $1`, agentID); err != nil {+ t.Fatalf("disable agent runtime: %v", err)+ }+ if _, err := svc.EnqueueChatTask(ctx, session, initiator, false); !errors.Is(err, ErrChatTaskAgentNoRuntime) {+ t.Fatalf("offline enqueue error = %v, want ErrChatTaskAgentNoRuntime", err)+ }+ var pending bool+ if err := pool.QueryRow(ctx, `SELECT pending_fresh FROM channel_chat_session_binding WHERE chat_session_id = $1`, chatSessionID).Scan(&pending); err != nil {+ t.Fatalf("load pending fresh after failure: %v", err)+ }+ if !pending {+ t.Fatal("failed enqueue consumed the pending fresh intent")+ }++ if _, err := pool.Exec(ctx, `UPDATE agent SET runtime_id = $2 WHERE id = $1`, agentID, runtimeID); err != nil {+ t.Fatalf("restore agent runtime: %v", err)+ }+ task, err := svc.EnqueueChatTask(ctx, session, initiator, false)+ if err != nil {+ t.Fatalf("EnqueueChatTask: %v", err)+ }+ if !task.ForceFreshSession {+ t.Fatal("task force_fresh_session = false, want true")+ }+ if err := pool.QueryRow(ctx, `SELECT pending_fresh FROM channel_chat_session_binding WHERE chat_session_id = $1`, chatSessionID).Scan(&pending); err != nil {+ t.Fatalf("load pending fresh after success: %v", err)+ }+ if pending {+ t.Fatal("successful enqueue did not consume the pending fresh intent")+ }+}+// TestEnqueueChatTaskIgnoresHandledCommandMedia is the counterpart of// TestEnqueueChatTaskDefersForChannelMediaAndPromotesWhenReady, which pins the// ordinary case. A channel `/issue` turn is answered synchronously by thediff --git a/server/migrations/265_channel_chat_pending_fresh.down.sql b/server/migrations/265_channel_chat_pending_fresh.down.sqlnew file mode 100644index 0000000000..11debbf2e1--- /dev/null+++ b/server/migrations/265_channel_chat_pending_fresh.down.sql@@ -0,0 +1,2 @@+ALTER TABLE channel_chat_session_binding+DROP COLUMN pending_fresh;diff --git a/server/migrations/265_channel_chat_pending_fresh.up.sql b/server/migrations/265_channel_chat_pending_fresh.up.sqlnew file mode 100644index 0000000000..89b23636bf--- /dev/null+++ b/server/migrations/265_channel_chat_pending_fresh.up.sql@@ -0,0 +1,2 @@+ALTER TABLE channel_chat_session_binding+ADD COLUMN pending_fresh BOOLEAN NOT NULL DEFAULT FALSE;diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.goindex 52cbb262e3..5f7000ed5a 100644--- a/server/pkg/db/generated/channel.sql.go+++ b/server/pkg/db/generated/channel.sql.go@@ -243,6 +243,17 @@ func (q *Queries) ClaimNextChannelMediaPendingObjectForReconcile(ctx context.Conreturn i, err}+const clearChannelChatSessionPendingFresh = `-- name: ClearChannelChatSessionPendingFresh :exec+UPDATE channel_chat_session_binding+SET pending_fresh = FALSE+WHERE chat_session_id = $1+`++func (q *Queries) ClearChannelChatSessionPendingFresh(ctx context.Context, chatSessionID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, clearChannelChatSessionPendingFresh, chatSessionID)+ return err+}+const consumeChannelBindingToken = `-- name: ConsumeChannelBindingToken :oneUPDATE channel_binding_tokenSET consumed_at = now()@@ -351,7 +362,7 @@ INSERT INTO channel_chat_session_binding () VALUES ($1, $2, $3, $4, $5, $6)-RETURNING id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at+RETURNING id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh`type CreateChannelChatSessionBindingParams struct {@@ -393,6 +404,7 @@ func (q *Queries) CreateChannelChatSessionBinding(ctx context.Context, arg Creat&i.LastThreadID,&i.Config,&i.CreatedAt,+ &i.PendingFresh,)return i, err}@@ -840,7 +852,7 @@ func (q *Queries) FindReusableChannelUserBinding(ctx context.Context, arg FindRe}const getChannelChatSessionBinding = `-- name: GetChannelChatSessionBinding :one-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at FROM channel_chat_session_binding+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh FROM channel_chat_session_bindingWHERE installation_id = $1 AND channel_chat_id = $2`@@ -865,12 +877,13 @@ func (q *Queries) GetChannelChatSessionBinding(ctx context.Context, arg GetChann&i.LastThreadID,&i.Config,&i.CreatedAt,+ &i.PendingFresh,)return i, err}const getChannelChatSessionBindingBySession = `-- name: GetChannelChatSessionBindingBySession :one-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at FROM channel_chat_session_binding+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh FROM channel_chat_session_bindingWHERE chat_session_id = $1AND channel_type = $2`@@ -898,12 +911,13 @@ func (q *Queries) GetChannelChatSessionBindingBySession(ctx context.Context, arg&i.LastThreadID,&i.Config,&i.CreatedAt,+ &i.PendingFresh,)return i, err}const getChannelChatSessionBindingBySessionAny = `-- name: GetChannelChatSessionBindingBySessionAny :one-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at FROM channel_chat_session_binding+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh FROM channel_chat_session_bindingWHERE chat_session_id = $1`@@ -927,6 +941,7 @@ func (q *Queries) GetChannelChatSessionBindingBySessionAny(ctx context.Context,&i.LastThreadID,&i.Config,&i.CreatedAt,+ &i.PendingFresh,)return i, err}@@ -1380,6 +1395,22 @@ func (q *Queries) ListChannelInstallationsByWorkspace(ctx context.Context, arg Lreturn items, nil}+const lockChannelChatSessionPendingFresh = `-- name: LockChannelChatSessionPendingFresh :one+SELECT pending_fresh FROM channel_chat_session_binding+WHERE chat_session_id = $1+FOR UPDATE+`++// EnqueueChatTask reads this under the same row lock and transaction that+// creates the task. A concurrent `/new` therefore lands either before this+// task and is consumed by it, or after this task and remains for the next one.+func (q *Queries) LockChannelChatSessionPendingFresh(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {+ row := q.db.QueryRow(ctx, lockChannelChatSessionPendingFresh, chatSessionID)+ var pending_fresh bool+ err := row.Scan(&pending_fresh)+ return pending_fresh, err+}+const lockChannelInstallationAppIDSlot = `-- name: LockChannelInstallationAppIDSlot :execSELECT pg_advisory_xact_lock(hashtext($1::text),@@ -1409,6 +1440,23 @@ func (q *Queries) LockChannelInstallationAppIDSlot(ctx context.Context, arg Lockreturn err}+const markChannelChatSessionPendingFresh = `-- name: MarkChannelChatSessionPendingFresh :one+UPDATE channel_chat_session_binding+SET pending_fresh = TRUE+WHERE chat_session_id = $1+RETURNING pending_fresh+`++// Persists a channel `/new` intent until the next chat task is successfully+// created. RETURNING makes a missing binding an error instead of silently+// acknowledging a fresh start that was never stored.+func (q *Queries) MarkChannelChatSessionPendingFresh(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {+ row := q.db.QueryRow(ctx, markChannelChatSessionPendingFresh, chatSessionID)+ var pending_fresh bool+ err := row.Scan(&pending_fresh)+ return pending_fresh, err+}+const markChannelInboundDedupProcessed = `-- name: MarkChannelInboundDedupProcessed :execrowsUPDATE channel_inbound_message_dedupSET processed_at = now()diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex e3ae0bdefe..884235f1e8 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -975,38 +975,6 @@ func (q *Queries) GetLatestAssistantChatMessageForSession(ctx context.Context, creturn i, err}-const getMostRecentUserChatMessage = `-- name: GetMostRecentUserChatMessage :one-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message-WHERE chat_session_id = $1 AND role = 'user'-ORDER BY created_at DESC-LIMIT 1-`--// Returns the most recent role='user' message in a session. Used by the-// Lark `/issue` command parser: when the user types `/issue` with no-// title, the spec falls back to "use the previous user message as the-// title". Bot replies (role='assistant') are excluded — only human-// input qualifies as a fallback title source.-func (q *Queries) GetMostRecentUserChatMessage(ctx context.Context, chatSessionID pgtype.UUID) (ChatMessage, error) {- row := q.db.QueryRow(ctx, getMostRecentUserChatMessage, chatSessionID)- var i ChatMessage- err := row.Scan(- &i.ID,- &i.ChatSessionID,- &i.Role,- &i.Content,- &i.TaskID,- &i.CreatedAt,- &i.FailureReason,- &i.ElapsedMs,- &i.MessageKind,- &i.ChannelMediaPendingUntil,- &i.ChannelIngested,- &i.QuickActions,- )- return i, err-}-const getOldestActiveChatSessionForCreatorAgent = `-- name: GetOldestActiveChatSessionForCreatorAgent :oneSELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id FROM chat_sessionWHERE workspace_id = $1diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex c6ada1dc78..5d403a64ba 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -294,6 +294,7 @@ type ChannelChatSessionBinding struct {LastThreadID pgtype.Text `json:"last_thread_id"`Config []byte `json:"config"`CreatedAt pgtype.Timestamptz `json:"created_at"`+ PendingFresh bool `json:"pending_fresh"`}type ChannelInboundAudit struct {diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sqlindex 9f71212aad..956fb458fd 100644--- a/server/pkg/db/queries/channel.sql+++ b/server/pkg/db/queries/channel.sql@@ -524,6 +524,28 @@ SET last_message_id = sqlc.narg('last_message_id'),last_thread_id = sqlc.narg('last_thread_id')WHERE chat_session_id = $1;+-- name: MarkChannelChatSessionPendingFresh :one+-- Persists a channel `/new` intent until the next chat task is successfully+-- created. RETURNING makes a missing binding an error instead of silently+-- acknowledging a fresh start that was never stored.+UPDATE channel_chat_session_binding+SET pending_fresh = TRUE+WHERE chat_session_id = $1+RETURNING pending_fresh;++-- name: LockChannelChatSessionPendingFresh :one+-- EnqueueChatTask reads this under the same row lock and transaction that+-- creates the task. A concurrent `/new` therefore lands either before this+-- task and is consumed by it, or after this task and remains for the next one.+SELECT pending_fresh FROM channel_chat_session_binding+WHERE chat_session_id = $1+FOR UPDATE;++-- name: ClearChannelChatSessionPendingFresh :exec+UPDATE channel_chat_session_binding+SET pending_fresh = FALSE+WHERE chat_session_id = $1;+-- name: DeleteChannelChatSessionBindingBySession :exec-- Application-layer integrity (replaces the old chat_session-FK ON DELETE-- CASCADE): drop the binding when its chat_session is deleted.diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 70d0fdc171..edef4a6eb7 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -1246,17 +1246,6 @@ SELECT EXISTS (UPDATE chat_session SET last_read_at = now()WHERE id = $1;--- name: GetMostRecentUserChatMessage :one--- Returns the most recent role='user' message in a session. Used by the--- Lark `/issue` command parser: when the user types `/issue` with no--- title, the spec falls back to "use the previous user message as the--- title". Bot replies (role='assistant') are excluded — only human--- input qualifies as a fallback title source.-SELECT * FROM chat_message-WHERE chat_session_id = $1 AND role = 'user'-ORDER BY created_at DESC-LIMIT 1;--- name: ChatSessionHasUserMessage :one-- Reports whether a session has any human (role='user') message yet. Used to-- scope the is_agent_intro self-introduction prompt to the very first,