Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
DH-106 为飞书接入补上 /new 会话指令 (MUL-3503) (#4396)
Wilson-Gb92e4a53fb93
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex ccd22b8215..90718a81d6 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -497,7 +497,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {// Enqueue a chat task after the message exists. For web chat the sender is// the authenticated request user (sessions are creator-only), so they are// the task initiator — surfaced to the agent under `## Task Initiator`.- task, err := h.TaskService.EnqueueChatTask(r.Context(), session, parseUUID(userID))+ task, err := h.TaskService.EnqueueChatTask(r.Context(), session, parseUUID(userID), false)if err != nil {writeError(w, http.StatusInternalServerError, "failed to enqueue chat task: "+err.Error())returndiff --git a/server/internal/integrations/lark/dispatcher.go b/server/internal/integrations/lark/dispatcher.goindex e024e7c1a5..b38d90d7e7 100644--- a/server/internal/integrations/lark/dispatcher.go+++ b/server/internal/integrations/lark/dispatcher.go@@ -5,6 +5,7 @@ import ("errors""fmt""log/slog"+ "sync""time""github.com/jackc/pgx/v5"@@ -23,15 +24,19 @@ import (// message is an interaction with the Bot (@-mention or reply to a// Bot card). For p2p messages this field is ignored.type InboundMessage struct {- EventType string- EventID string- AppID string- ChatID ChatID- ChatType ChatType- MessageID string- SenderOpenID OpenID- Body string- AddressedToBot bool+ EventType string+ EventID string+ AppID string+ ChatID ChatID+ ChatType ChatType+ MessageID string+ SenderOpenID OpenID+ Body string+ // ForceFreshSession marks this dispatch as a one-off fresh start:+ // the daemon should skip prior session resume when it claims the+ // resulting chat task.+ ForceFreshSession bool+ AddressedToBot bool// MessageType is the raw Lark msg_type ("text", "post",// "merge_forward", "image", "interactive", …). The decoder@@ -161,7 +166,7 @@ type IssueCreator interface {// the Dispatcher is small enough that depending on the whole// TaskService struct is gratuitous.type ChatTaskEnqueuer interface {- EnqueueChatTask(ctx context.Context, session db.ChatSession, initiatorUserID pgtype.UUID) (db.AgentTaskQueue, error)+ EnqueueChatTask(ctx context.Context, session db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error)}// DispatcherQueries is the narrow subset of *db.Queries the Dispatcher@@ -242,6 +247,13 @@ type Dispatcher struct {// config) the run fires inline with no debounce — a zero-length// window, not a separate code path.batcher *pendingBatcher++ // pendingFresh tracks whether any message in the current debounced+ // session window asked for a fresh run. The debouncer intentionally+ // keeps the latest flush closure so the latest sender wins, but the+ // fresh-start directive is sticky across the window.+ pendingFreshMu sync.Mutex+ pendingFresh map[string]bool}// FlushReplyFunc matches OutcomeReplier.Reply so the production replier can@@ -601,7 +613,8 @@ func (d *Dispatcher) processClaimed(ctx context.Context, msg InboundMessage, ins// message's installation + InboundMessage so the offline/archived notice,// if any, targets the right chat; the latest message in a window wins.func (d *Dispatcher) scheduleRun(inst Installation, msg InboundMessage, sessionID pgtype.UUID, initiatorUserID pgtype.UUID) {- flush := func() { d.flushChatRun(inst, msg, sessionID, initiatorUserID) }+ key := keyForSession(sessionID)+ flush := func() { d.flushChatRun(inst, msg, sessionID, initiatorUserID, msg.ForceFreshSession) }if d.batcher == nil {// Batching disabled (unit tests / degenerate config): trigger the// run immediately. Production always installs a batcher via@@ -609,7 +622,13 @@ func (d *Dispatcher) scheduleRun(inst Installation, msg InboundMessage, sessionIflush()return}- d.batcher.Schedule(keyForSession(sessionID), flush)+ if msg.ForceFreshSession {+ d.markPendingFresh(key)+ }+ flush = func() {+ d.flushChatRun(inst, msg, sessionID, initiatorUserID, d.takePendingFresh(key, msg.ForceFreshSession))+ }+ d.batcher.Schedule(key, flush)}// flushChatRun is the debounced run-trigger. It runs once per silence@@ -621,7 +640,7 @@ func (d *Dispatcher) scheduleRun(inst Installation, msg InboundMessage, sessionI// returned to a caller (the message is already ACKed and durable), so they// are logged: a failed enqueue leaves the message in the session to be// picked up by the next message's run.-func (d *Dispatcher) flushChatRun(inst Installation, msg InboundMessage, sessionID pgtype.UUID, initiatorUserID pgtype.UUID) {+func (d *Dispatcher) flushChatRun(inst Installation, msg InboundMessage, sessionID pgtype.UUID, initiatorUserID pgtype.UUID, forceFreshSession bool) {ctx, cancel := context.WithTimeout(context.Background(), chatRunFlushTimeout)defer cancel()@@ -633,7 +652,7 @@ func (d *Dispatcher) flushChatRun(inst Installation, msg InboundMessage, session)return}- if _, err := d.TaskService.EnqueueChatTask(ctx, session, initiatorUserID); err != nil {+ if _, err := d.TaskService.EnqueueChatTask(ctx, session, initiatorUserID, forceFreshSession); err != nil {switch {case errors.Is(err, service.ErrChatTaskAgentNoRuntime):d.emitFlushReply(ctx, inst, msg, sessionID, OutcomeAgentOffline)@@ -652,6 +671,26 @@ func (d *Dispatcher) flushChatRun(inst Installation, msg InboundMessage, session}}+func (d *Dispatcher) markPendingFresh(key string) {+ d.pendingFreshMu.Lock()+ defer d.pendingFreshMu.Unlock()+ if d.pendingFresh == nil {+ d.pendingFresh = make(map[string]bool)+ }+ d.pendingFresh[key] = true+}++func (d *Dispatcher) takePendingFresh(key string, fallback bool) bool {+ d.pendingFreshMu.Lock()+ defer d.pendingFreshMu.Unlock()+ fresh := fallback+ if d.pendingFresh != nil {+ fresh = fresh || d.pendingFresh[key]+ delete(d.pendingFresh, key)+ }+ return fresh+}+// emitFlushReply delivers an offline/archived notice for a flushed run.func (d *Dispatcher) emitFlushReply(ctx context.Context, inst Installation, msg InboundMessage, sessionID pgtype.UUID, outcome Outcome) {if d.FlushReply == nil {diff --git a/server/internal/integrations/lark/dispatcher_test.go b/server/internal/integrations/lark/dispatcher_test.goindex 6bb19f9fc0..932ea150b7 100644--- a/server/internal/integrations/lark/dispatcher_test.go+++ b/server/internal/integrations/lark/dispatcher_test.go@@ -304,11 +304,13 @@ type fakeEnqueuer struct {task db.AgentTaskQueueerr errorlastInitiatorUID pgtype.UUID+ lastForceFresh bool}-func (f *fakeEnqueuer) EnqueueChatTask(ctx context.Context, _ db.ChatSession, initiatorUserID pgtype.UUID) (db.AgentTaskQueue, error) {+func (f *fakeEnqueuer) EnqueueChatTask(ctx context.Context, _ db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error) {f.called++f.lastInitiatorUID = initiatorUserID+ f.lastForceFresh = forceFreshSessionreturn f.task, f.err}@@ -555,6 +557,44 @@ func TestDispatcher_PlainMessageEnqueuesTask(t *testing.T) {t.Fatalf("p2p task initiator should be sender; got %+v want %+v",enq.lastInitiatorUID, queries.userBinding.MulticaUserID)}+ if enq.lastForceFresh {+ t.Fatalf("plain chat message must not force a fresh session")+ }+}++func TestDispatcher_FreshMessageEnqueuesFreshTask(t *testing.T) {+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}+ enq := &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}}+ d := &Dispatcher{+ Queries: queries,+ Chat: chat,+ Audit: &fakeAudit{},+ TaskService: enq,+ }++ _, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "rebuild the plan",+ ForceFreshSession: true,+ MessageID: "msg-fresh",+ })+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if enq.called != 1 {+ t.Fatalf("expected exactly one EnqueueChatTask at flush; called=%d", enq.called)+ }+ if !enq.lastForceFresh {+ t.Fatalf("fresh Lark message should force a fresh chat task")+ }}// TestDispatcher_ForwardsThreadIDToAppend verifies the dispatcher@@ -1182,6 +1222,47 @@ func TestDispatcher_DebounceCoalescesRunTrigger(t *testing.T) {}}+func TestDispatcher_DebouncePreservesFreshAcrossWindow(t *testing.T) {+ // If any message in the coalesced window is /new, the single+ // resulting run must be fresh even though the latest sender/message+ // still supplies the reply target and initiator.+ sessionID := validUUID(0x66)+ queries := &fakeQueries{+ installationByApp: activeInstallation(),+ userBinding: boundUser(),+ chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},+ }+ chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}+ enq := &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}}+ f := &fakeTimerFactory{}+ d := &Dispatcher{Queries: queries, Chat: chat, Audit: &fakeAudit{}, TaskService: enq}+ d.batcher = newTestBatcher(f)++ send := func(id string, forceFresh bool) {+ if _, err := d.Handle(context.Background(), InboundMessage{+ AppID: "ok",+ ChatType: ChatTypeP2P,+ SenderOpenID: "ou_user_a",+ Body: "hi",+ ForceFreshSession: forceFresh,+ MessageID: id,+ }); err != nil {+ t.Fatalf("unexpected error for %s: %v", id, err)+ }+ }++ send("m-fresh", true)+ send("m-normal", false)+ f.fireArmed()++ if enq.called != 1 {+ t.Fatalf("a coalesced burst must enqueue exactly once; called=%d", enq.called)+ }+ if !enq.lastForceFresh {+ t.Fatalf("fresh directive should stick across the debounced window")+ }+}+// TestDispatcher_LatestSenderWinsAsInitiator pins the MUL-2645 batching// decision: when several people speak in one chat within a single silence// window, the coalesced run's initiator is the LAST sender. The debouncer keepsdiff --git a/server/internal/integrations/lark/fresh_command.go b/server/internal/integrations/lark/fresh_command.gonew file mode 100644index 0000000000..193a74b2ff--- /dev/null+++ b/server/internal/integrations/lark/fresh_command.go@@ -0,0 +1,66 @@+package lark++import "strings"++const (+ newCommandPrefix = "/new"+)++// FreshSessionCommand is the normalized fresh-start directive extracted from a+// Lark inbound message. Body is the user prompt with the directive removed.+type FreshSessionCommand struct {+ Body string+}++// parseFreshSessionCommand extracts a first-line /new command from a message+// body. Matching follows the /issue command rules: case-sensitive,+// token-bounded, and only the first non-empty line can be a command. That+// means /new and /issue are mutually exclusive on the same first line.+func parseFreshSessionCommand(body string) (*FreshSessionCommand, bool) {+ lines := strings.Split(body, "\n")++ firstIdx := -1+ for i, line := range lines {+ if strings.TrimSpace(line) != "" {+ firstIdx = i+ break+ }+ }+ if firstIdx == -1 {+ return nil, false+ }++ first := lines[firstIdx]+ trimmed := strings.TrimLeft(first, " \t")+ prefix, ok := matchedFreshPrefix(trimmed)+ if !ok {+ return nil, false+ }++ rest := trimmed[len(prefix):]+ if rest != "" {+ r0 := rest[0]+ if r0 != ' ' && r0 != '\t' {+ return nil, false+ }+ }++ bodyParts := make([]string, 0, 2)+ if firstLineBody := strings.TrimSpace(rest); firstLineBody != "" {+ bodyParts = append(bodyParts, firstLineBody)+ }+ if firstIdx+1 < len(lines) {+ bodyParts = append(bodyParts, strings.Join(lines[firstIdx+1:], "\n"))+ }+ stripped := strings.TrimRight(strings.Join(bodyParts, "\n"), " \t\n")+ return &FreshSessionCommand{Body: stripped}, true+}++func matchedFreshPrefix(line string) (string, bool) {+ switch {+ case strings.HasPrefix(line, newCommandPrefix):+ return newCommandPrefix, true+ default:+ return "", false+ }+}diff --git a/server/internal/integrations/lark/fresh_command_test.go b/server/internal/integrations/lark/fresh_command_test.gonew file mode 100644index 0000000000..b7beef9053--- /dev/null+++ b/server/internal/integrations/lark/fresh_command_test.go@@ -0,0 +1,75 @@+package lark++import "testing"++func TestParseFreshSessionCommand(t *testing.T) {+ tests := []struct {+ name string+ body string+ wantMatch bool+ wantBody string+ }{+ {+ name: "new with same-line body",+ body: "/new start from scratch",+ wantMatch: true,+ wantBody: "start from scratch",+ },+ {+ name: "leading blank lines tolerated",+ body: "\n\n/new re-check the deploy",+ wantMatch: true,+ wantBody: "re-check the deploy",+ },+ {+ name: "multi-line body preserved",+ body: "/new title\nline one\nline two",+ wantMatch: true,+ wantBody: "title\nline one\nline two",+ },+ {+ name: "command alone produces empty body",+ body: "/new",+ wantMatch: true,+ wantBody: "",+ },+ {+ name: "prefix of token rejected",+ body: "/newness is not a command",+ wantMatch: false,+ },+ {+ name: "mid-sentence command rejected",+ body: "please /new this run",+ wantMatch: false,+ },+ {+ name: "wrong case rejected",+ body: "/New help",+ wantMatch: false,+ },+ {+ name: "normal body rejected",+ body: "help me normally",+ wantMatch: false,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ cmd, ok := parseFreshSessionCommand(tc.body)+ if ok != tc.wantMatch {+ t.Fatalf("match=%v want %v (cmd=%+v)", ok, tc.wantMatch, cmd)+ }+ if !tc.wantMatch {+ if cmd != nil {+ t.Fatalf("expected nil command, got %+v", cmd)+ }+ return+ }+ if cmd.Body != tc.wantBody {+ t.Errorf("body=%q want %q", cmd.Body, tc.wantBody)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/inbound_enricher.go b/server/internal/integrations/lark/inbound_enricher.goindex 452d304664..9c573a779b 100644--- a/server/internal/integrations/lark/inbound_enricher.go+++ b/server/internal/integrations/lark/inbound_enricher.go@@ -126,6 +126,15 @@ func NewInboundEnricher(client APIClient, cfg InboundEnricherConfig) Enricher {// context attached to a turn a workspace member explicitly directed at// the Bot.func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, creds InstallationCredentials) InboundMessage {+ freshSource := msg.CommandBody+ if freshSource == "" {+ freshSource = msg.Body+ }+ if cmd, ok := parseFreshSessionCommand(freshSource); ok {+ msg.ForceFreshSession = true+ msg.Body = cmd.Body+ }+isForward := msg.MessageType == larkMsgTypeMergeForwardwantRecent := e.recentContextSize > 0 && msg.ChatType == ChatTypeGroup && msg.AddressedToBotif msg.ParentID == "" && !isForward && !wantRecent {diff --git a/server/internal/integrations/lark/inbound_enricher_test.go b/server/internal/integrations/lark/inbound_enricher_test.goindex 2897cd4041..0a60e47dda 100644--- a/server/internal/integrations/lark/inbound_enricher_test.go+++ b/server/internal/integrations/lark/inbound_enricher_test.go@@ -166,6 +166,58 @@ func TestEnrichMergeForward(t *testing.T) {}}+func TestEnrichFreshSessionStripsCommandAndSetsFlag(t *testing.T) {+ t.Parallel()+ fake := newEnricherFake()+ in := InboundMessage{+ MessageType: "text",+ Body: "/new rebuild the plan",+ CommandBody: "/new rebuild the plan",+ }++ out := enrich(t, fake, in, InboundEnricherConfig{})++ if !out.ForceFreshSession {+ t.Fatalf("ForceFreshSession should be true for /new")+ }+ if out.Body != "rebuild the plan" {+ t.Fatalf("Body should have directive stripped; got %q", out.Body)+ }+ if out.CommandBody != "/new rebuild the plan" {+ t.Fatalf("CommandBody should remain the original command source; got %q", out.CommandBody)+ }+}++func TestEnrichFreshSessionPreservesQuotedContext(t *testing.T) {+ t.Parallel()+ fake := newEnricherFake()+ fake.byID["om_parent"] = []LarkMessage{+ textMsg("om_parent", "ou_a", "old context", "1000"),+ }+ in := InboundMessage{+ MessageType: "text",+ MessageID: "om_child",+ Body: "/new handle this independently",+ CommandBody: "/new handle this independently",+ ParentID: "om_parent",+ }++ out := enrich(t, fake, in, InboundEnricherConfig{})++ if !out.ForceFreshSession {+ t.Fatalf("ForceFreshSession should be true for /new")+ }+ if !strings.Contains(out.Body, `<quoted_message message_id="om_parent"`) {+ t.Fatalf("quoted context should be preserved; body=%q", out.Body)+ }+ if !strings.HasSuffix(out.Body, "handle this independently") {+ t.Fatalf("directive should be stripped from user prose; body=%q", out.Body)+ }+ if strings.Contains(out.Body, "/new") {+ t.Fatalf("stored/enriched body should not include the directive; body=%q", out.Body)+ }+}+// TestEnrichMergeForwardSortsByCreateTime ensures children are ordered// chronologically regardless of the order Lark returns them.func TestEnrichMergeForwardSortsByCreateTime(t *testing.T) {diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 79e8154394..22f227c629 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -727,7 +727,11 @@ var ErrChatTaskAgentNoRuntime = errors.New("chat task: agent has no runtime")// passes the request user; the lark dispatcher passes the inbound sender of the// latest message in the silence window. Stored on the task so the daemon brief// can attribute the run to the right person. See MUL-2645.-func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSession, initiatorUserID pgtype.UUID) (db.AgentTaskQueue, error) {+//+// forceFreshSession applies only to the task created by this call. The daemon+// uses it to skip prior chat-session resume for this dispatch without clearing+// the chat session's stored resume pointer for future normal messages.+func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error) {agent, err := s.Queries.GetAgent(ctx, chatSession.AgentID)if err != nil {slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)@@ -746,6 +750,10 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSePriority: 2, // medium priority for chatChatSessionID: chatSession.ID,InitiatorUserID: initiatorUserID,+ ForceFreshSession: pgtype.Bool{+ Bool: forceFreshSession,+ Valid: true,+ },})if err != nil {slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 07e85165f2..d83657ddbb 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -88,17 +88,24 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa}const createChatTask = `-- name: CreateChatTask :one-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id, initiator_user_id)-VALUES ($1, $2, NULL, 'queued', $3, $4, $5)+INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, chat_session_id,+ initiator_user_id, force_fresh_session+)+VALUES (+ $1, $2, NULL, 'queued', $3, $4, $5,+ COALESCE($6::boolean, FALSE)+)RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at`type CreateChatTaskParams struct {- AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`- Priority int32 `json:"priority"`- ChatSessionID pgtype.UUID `json:"chat_session_id"`- InitiatorUserID pgtype.UUID `json:"initiator_user_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ Priority int32 `json:"priority"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`+ ForceFreshSession pgtype.Bool `json:"force_fresh_session"`}func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams) (AgentTaskQueue, error) {@@ -108,6 +115,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)arg.Priority,arg.ChatSessionID,arg.InitiatorUserID,+ arg.ForceFreshSession,)var i AgentTaskQueueerr := row.Scan(diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 269cea67f3..12a56e6134 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -108,8 +108,14 @@ SELECT * FROM chat_messageWHERE id = $1;-- name: CreateChatTask :one-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id, initiator_user_id)-VALUES ($1, $2, NULL, 'queued', $3, $4, $5)+INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, chat_session_id,+ initiator_user_id, force_fresh_session+)+VALUES (+ $1, $2, NULL, 'queued', $3, $4, $5,+ COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE)+)RETURNING *;-- name: GetLastChatTaskSession :one