oficina / equipo Public

Organise conversation into collapsible project threads

Projects now have closed-by-default groups with status, unread and needs-you indicators, plus explicitly scoped prompting. Ambiguous older messages stay in General rather than being assigned by guesswork, and existing message and action elements are reused.

Added tests and an interactive visual preview for review. JavaScript syntax and migration smoke checks passed, but dependency downloads and Chromium execution were blocked, so full tests and screenshot capture remain unverified.

Equipo task tkr23w5r4zb5, Engineering step attempt 1.
Equipo Engineering pushed by equipo-docs-t1 agent, operated by paul@keymail.dev c8ac56adf9b1ad085ee71dd53b46c0f45ff6a160 parent 518203e
25 files changed, +535 −29
  • internal/equipo/chat/merge.go +1 −1
  • internal/equipo/chat/models.go +2 −0
  • internal/equipo/chat/project_threads_test.go +64 −0
  • internal/equipo/chat/projects.go +2 −2
  • internal/equipo/chat/publish.go +1 −1
  • internal/equipo/chat/runner.go +1 −1
  • internal/equipo/chat/store.go +35 −9
  • internal/equipo/chat/tools.go +1 −1
  • internal/equipo/chat_days.go +1 −1
  • internal/equipo/chat_page.go +5 −3
  • internal/equipo/migrations/0081_project_threads.sql +3 −0
  • internal/equipo/migrations/schema.sql +2 −2
  • internal/equipo/static/chat-anchor.js +1 −0
  • internal/equipo/static/chat-stream.js +11 −3
  • internal/equipo/static/equipo.css +12 −0
  • internal/equipo/static/project-threads.js +127 −0
  • internal/equipo/templates/chat.html +6 −4
  • internal/equipo/templates/chrome.html +1 −1
  • internal/headless/browser_project_threads_test.go +44 −0
  • internal/wire/api.go +3 −0
  • release/preview.json +1 −0
  • release/project-threads/README.md +32 −0
  • release/project-threads/browser-test.js +36 −0
  • release/project-threads/index.html +16 −0
  • release/project-threads/project-threads.js +127 −0

CI failed — run details

diff --git a/internal/equipo/chat/merge.go b/internal/equipo/chat/merge.go
index 446e833e..f0424ac9 100644
--- a/internal/equipo/chat/merge.go
+++ b/internal/equipo/chat/merge.go
@@ -254,7 +254,7 @@ func (t *txn) mergedLine(k *taskRecord, key, project string) error {
if err := t.db.Model(&messageRecord{}).Where("person = ? AND idempotency_key = ?", k.Creator, "merged:"+k.ID).Count(&n).Error; err != nil || n > 0 {
return err
}
- m := messageRecord{ID: newID("m_"), Person: k.Creator, IdempotencyKey: "merged:" + k.ID, Role: wire.RoleCoordinator, Text: text, Revision: 1, CreatedAt: t.now()}
+ m := messageRecord{ProjectID: k.ProjectID, ID: newID("m_"), Person: k.Creator, IdempotencyKey: "merged:" + k.ID, Role: wire.RoleCoordinator, Text: text, Revision: 1, CreatedAt: t.now()}
if err := t.db.Create(&m).Error; err != nil {
return err
}
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index bfa1fb0e..e3149d69 100644
--- a/internal/equipo/chat/models.go
+++ b/internal/equipo/chat/models.go
@@ -10,6 +10,7 @@ import "time"
var Models = []any{&turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}}
type turnRecord struct {
+ ProjectID string
ID string `gorm:"primaryKey"`
Person string `gorm:"index:chat_turn_person,priority:1"`
State string `gorm:"index:chat_turn_person,priority:2"`
@@ -42,6 +43,7 @@ func (turnRecord) TableName() string { return "chat_turns" }
// orders by it. Coordinator replies use the key "reply:<turn>". A key is
// unique per person and lane.
type messageRecord struct {
+ ProjectID string
Seq int64 `gorm:"primaryKey"`
ID string `gorm:"uniqueIndex:chat_message_id"`
Person string `gorm:"index:chat_message_person;uniqueIndex:chat_message_key,priority:1"`
diff --git a/internal/equipo/chat/project_threads_test.go b/internal/equipo/chat/project_threads_test.go
new file mode 100644
index 00000000..96a0245d
--- /dev/null
+++ b/internal/equipo/chat/project_threads_test.go
@@ -0,0 +1,64 @@
+package chat
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+func TestProjectThreadSendScope(t *testing.T) {
+ r := newMeteredRig(t)
+ ctx := context.Background()
+ const person = "owner@example.com"
+ now := time.Now().UTC()
+ for _, id := range []string{"p_one", "p_two"} {
+ if err := r.s.db.G.Create(&projectRecord{ID: id, Repo: "example.com/team/" + id, State: wire.ProjectActive, AddedBy: person, Revision: 1, CreatedAt: now, UpdatedAt: now}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Hold dispatch so we can exercise batching without a runner.
+ if err := r.s.db.G.Create(&turnRecord{ID: "t_busy", Person: person, State: wire.TurnRunning, Dispatched: true, Revision: 1, CreatedAt: now, UpdatedAt: now}).Error; err != nil {
+ t.Fatal(err)
+ }
+ send := func(project, key string) wire.Sent {
+ t.Helper()
+ out, created, err := r.s.Send(ctx, person, wire.SendMessage{ProjectID: project, Text: "same words", IdempotencyKey: key})
+ if err != nil || !created {
+ t.Fatalf("send: %v, created %v", err, created)
+ }
+ if out.Message.ProjectID != project || out.Turn.ProjectID != project {
+ t.Fatalf("scope lost: %+v", out)
+ }
+ return out
+ }
+ a := send("p_one", "one")
+ b := send("p_two", "two")
+ c := send("p_one", "three")
+ if a.Turn.ID == b.Turn.ID || a.Turn.ID == c.Turn.ID || b.Turn.ID == c.Turn.ID {
+ t.Fatal("cross-project batches reordered the conversation")
+ }
+ general := send("", "general")
+ if general.Message.ProjectID != "" {
+ t.Fatal("General was attributed")
+ }
+ again, created, err := r.s.Send(ctx, person, wire.SendMessage{ProjectID: "p_one", Text: "same words", IdempotencyKey: "one"})
+ if err != nil || created || again.Message.ID != a.Message.ID {
+ t.Fatalf("retry: %+v %v %v", again, created, err)
+ }
+ _, _, err = r.s.Send(ctx, person, wire.SendMessage{ProjectID: "p_two", Text: "same words", IdempotencyKey: "one"})
+ if !errors.Is(err, ErrConflict) {
+ t.Fatalf("scope-changing retry: %v", err)
+ }
+ _, _, err = r.s.Send(ctx, person, wire.SendMessage{ProjectID: "unknown", Text: "hello", IdempotencyKey: "missing"})
+ if !errors.Is(err, ErrNotFound) {
+ t.Fatalf("unknown project: %v", err)
+ }
+ r.removed = true
+ _, _, err = r.s.Send(ctx, person, wire.SendMessage{ProjectID: "p_one", Text: "hello", IdempotencyKey: "removed"})
+ if !errors.Is(err, ErrForbidden) {
+ t.Fatalf("removed member: %v", err)
+ }
+}
diff --git a/internal/equipo/chat/projects.go b/internal/equipo/chat/projects.go
index c5946405..9173a56f 100644
--- a/internal/equipo/chat/projects.go
+++ b/internal/equipo/chat/projects.go
@@ -724,7 +724,7 @@ func (t *txn) answerQuestion(person string, c cardRecord, in wire.AnswerCard) (o
}
// The card points at its answer before the answer is dispatched, so
// the coordinator gets the question (or the replaced project) with it.
- sent, _, err := t.send(wire.LaneCoordinator, person, "card:"+c.ID, in.Choice, nil, func(m messageRecord) error {
+ sent, _, err := t.sendScoped(wire.LaneCoordinator, person, "card:"+c.ID, in.Choice, nil, func(m messageRecord) error {
c.State, c.Choice, c.AnswerMessage = wire.CardAnswered, in.Choice, m.ID
if c.Kind == wire.CardProject {
c.State = wire.CardChanged
@@ -735,7 +735,7 @@ func (t *txn) answerQuestion(person string, c cardRecord, in wire.AnswerCard) (o
// The work the answer starts is the hand-off's, when the
// card's turn was.
return t.followAnswer(c, m)
- })
+ }, c.ProjectID)
if err != nil {
return out, current, err
}
diff --git a/internal/equipo/chat/publish.go b/internal/equipo/chat/publish.go
index ffdda5e2..7619a6b7 100644
--- a/internal/equipo/chat/publish.go
+++ b/internal/equipo/chat/publish.go
@@ -450,7 +450,7 @@ func (t *txn) publishEnded(k *taskRecord, s *stepRecord) error {
return err
}
if n == 0 {
- m := messageRecord{ID: newID("m_"), Person: k.Creator, IdempotencyKey: idem, Role: wire.RoleCoordinator, Text: text, Revision: 1, CreatedAt: t.now()}
+ m := messageRecord{ProjectID: k.ProjectID, ID: newID("m_"), Person: k.Creator, IdempotencyKey: idem, Role: wire.RoleCoordinator, Text: text, Revision: 1, CreatedAt: t.now()}
if err := t.db.Create(&m).Error; err != nil {
return err
}
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index 860e9e05..d6c6439c 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -464,7 +464,7 @@ func (t *txn) reply(l Lease, v *wire.Reply) error {
if r.Lane == wire.LaneAssistant {
role = wire.RoleAssistant
}
- m := messageRecord{ID: newID("m_"), Person: r.Person, IdempotencyKey: "reply:" + r.ID, Role: role, Text: v.Text, TurnID: r.ID, Revision: 1, CreatedAt: t.now(), Switched: asJSON(v.Switched), Lane: r.Lane}
+ m := messageRecord{ProjectID: r.ProjectID, ID: newID("m_"), Person: r.Person, IdempotencyKey: "reply:" + r.ID, Role: role, Text: v.Text, TurnID: r.ID, Revision: 1, CreatedAt: t.now(), Switched: asJSON(v.Switched), Lane: r.Lane}
if err = t.db.Create(&m).Error; err != nil {
return err
}
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 10e43f6a..7dcfe0bb 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -208,7 +208,7 @@ func (t *txn) turnEvent(r turnRecord) error {
}
func messageView(m messageRecord) wire.Message {
- v := wire.Message{ID: m.ID, Revision: m.Revision, Role: m.Role, Text: m.Text, TurnID: m.TurnID, CreatedAt: m.CreatedAt}
+ v := wire.Message{ProjectID: m.ProjectID, ID: m.ID, Revision: m.Revision, Role: m.Role, Text: m.Text, TurnID: m.TurnID, CreatedAt: m.CreatedAt}
if m.Switched != "" {
v.Switched = &wire.Switched{}
if json.Unmarshal([]byte(m.Switched), v.Switched) != nil {
@@ -231,7 +231,7 @@ func (t *txn) turnView(r turnRecord) (wire.Turn, error) {
if err := t.db.Model(&messageRecord{}).Where("turn_id = ? AND role = ?", r.ID, wire.RolePerson).Order("seq").Pluck("id", &ids).Error; err != nil {
return wire.Turn{}, err
}
- v := wire.Turn{ID: r.ID, Revision: r.Revision, Kind: r.Kind, State: r.State, Reason: r.Reason, Attempt: r.Attempt, MessageIDs: ids, ReplyID: r.ReplyID, Connection: r.Connection, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
+ v := wire.Turn{ProjectID: r.ProjectID, ID: r.ID, Revision: r.Revision, Kind: r.Kind, State: r.State, Reason: r.Reason, Attempt: r.Attempt, MessageIDs: ids, ReplyID: r.ReplyID, Connection: r.Connection, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
if r.Timing != "" && r.State == wire.TurnReplied {
v.Timing = &wire.TurnTiming{}
if err := json.Unmarshal([]byte(r.Timing), v.Timing); err != nil {
@@ -298,7 +298,11 @@ func (t *txn) dispatch(r *turnRecord) error {
// messages, nor those of a batch still waiting behind it (a batch too
// big for one frame goes as several turns, one after another).
var prior []messageRecord
- if err := t.db.Where("person = ? AND coalesce(lane, '') = ? AND turn_id <> ? AND turn_id NOT IN (SELECT id FROM chat_turns WHERE person = ? AND dispatched = ? AND state = ?)", r.Person, r.Lane, r.ID, r.Person, false, wire.TurnQueued).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&prior).Error; err != nil {
+ history := t.db
+ if r.ProjectID != "" {
+ history = history.Where("project_id = ?", r.ProjectID)
+ }
+ if err := history.Where("person = ? AND coalesce(lane, '') = ? AND turn_id <> ? AND turn_id NOT IN (SELECT id FROM chat_turns WHERE person = ? AND dispatched = ? AND state = ?)", r.Person, r.Lane, r.ID, r.Person, false, wire.TurnQueued).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&prior).Error; err != nil {
return err
}
tail := make([]wire.TailMessage, 0, len(prior))
@@ -326,6 +330,13 @@ func (t *txn) dispatch(r *turnRecord) error {
if text, err = t.handoffContext(m, text); err != nil {
return err
}
+ if r.ProjectID != "" {
+ var p projectRecord
+ if err := t.db.Where("id = ?", r.ProjectID).First(&p).Error; err != nil {
+ return err
+ }
+ text = "Project-scoped request for " + p.Repo + " (" + p.ID + "):\n" + text
+ }
texts = append(texts, text)
attached = append(attached, names[m.ID])
}
@@ -485,7 +496,7 @@ func (s *Store) Send(ctx context.Context, person string, in wire.SendMessage) (o
return err
}
var err error
- out, created, err = t.send(wire.LaneCoordinator, person, in.IdempotencyKey, in.Text, in.Attachments, nil)
+ out, created, err = t.sendScoped(wire.LaneCoordinator, person, in.IdempotencyKey, in.Text, in.Attachments, nil, in.ProjectID)
return err
})
return out, created, err
@@ -501,10 +512,14 @@ func validKey(key string) bool {
// the person's unsent uploads), inside a write transaction. before runs
// after the message exists and before it can be dispatched.
func (t *txn) send(lane, person, key, text string, files []string, before func(messageRecord) error) (out wire.Sent, created bool, err error) {
+ return t.sendScoped(lane, person, key, text, files, before, "")
+}
+
+func (t *txn) sendScoped(lane, person, key, text string, files []string, before func(messageRecord) error, project string) (out wire.Sent, created bool, err error) {
var prior messageRecord
err = t.db.Where("person = ? AND idempotency_key = ? AND coalesce(lane, '') = ?", person, key, lane).First(&prior).Error
if err == nil {
- if prior.BodyHash != sendHash(text, files) {
+ if prior.BodyHash != sendHash(text, files) || prior.ProjectID != project {
return out, false, ErrConflict
}
var turn turnRecord
@@ -521,6 +536,17 @@ func (t *txn) send(lane, person, key, text string, files []string, before func(m
if !errors.Is(err, gorm.ErrRecordNotFound) {
return out, false, err
}
+ // Scope is an existing team project, not a new access boundary. Check
+ // only a new send: a retry still returns its receipt after removal.
+ if project != "" {
+ var p projectRecord
+ if err := t.db.Where("id = ? AND state = ?", project, wire.ProjectActive).First(&p).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return out, false, ErrNotFound
+ }
+ return out, false, err
+ }
+ }
now := t.now()
var turn turnRecord
// The message joins the newest waiting batch, unless that batch would
@@ -531,8 +557,8 @@ func (t *txn) send(lane, person, key, text string, files []string, before func(m
if err != nil {
return out, false, err
}
- err = t.db.Where("person = ? AND coalesce(lane, '') = ? AND dispatched = ? AND state = ? AND coalesce(kind, '') = '' AND NOT EXISTS (SELECT 1 FROM chat_handoff_turns WHERE turn_id = chat_turns.id)", person, lane, false, wire.TurnQueued).Order("created_at DESC, id DESC").First(&turn).Error
- fresh := errors.Is(err, gorm.ErrRecordNotFound) || err == nil && alone
+ err = t.db.Where("person = ? AND coalesce(lane, '') = ? AND dispatched = ? AND state = ? AND coalesce(kind, '') = '' AND NOT EXISTS (SELECT 1 FROM chat_handoff_turns WHERE turn_id = chat_turns.id)", person, lane, false, wire.TurnQueued).Order("(SELECT max(seq) FROM chat_messages WHERE turn_id = chat_turns.id) DESC").First(&turn).Error
+ fresh := errors.Is(err, gorm.ErrRecordNotFound) || err == nil && (alone || turn.ProjectID != project)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return out, false, err
}
@@ -542,12 +568,12 @@ func (t *txn) send(lane, person, key, text string, files []string, before func(m
}
}
if fresh {
- turn = turnRecord{ID: newID("t_"), Person: person, State: wire.TurnQueued, Attempt: 1, CreatedAt: now, UpdatedAt: now, Lane: lane}
+ turn = turnRecord{ProjectID: project, ID: newID("t_"), Person: person, State: wire.TurnQueued, Attempt: 1, CreatedAt: now, UpdatedAt: now, Lane: lane}
if err = t.db.Create(&turn).Error; err != nil {
return out, false, err
}
}
- m := messageRecord{ID: newID("m_"), Person: person, IdempotencyKey: key, BodyHash: sendHash(text, files), Role: wire.RolePerson, Text: text, TurnID: turn.ID, Revision: 1, CreatedAt: now, Lane: lane}
+ m := messageRecord{ProjectID: project, ID: newID("m_"), Person: person, IdempotencyKey: key, BodyHash: sendHash(text, files), Role: wire.RolePerson, Text: text, TurnID: turn.ID, Revision: 1, CreatedAt: now, Lane: lane}
if err = t.db.Create(&m).Error; err != nil {
return out, false, err
}
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index e73b0aa1..99a91874 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -731,7 +731,7 @@ func (t *txn) askPerson(r turnRecord, question string, options []string) (wire.T
}
raw, _ := json.Marshal(options)
now := t.now()
- c := cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardQuestion, State: wire.CardOpen, TurnID: r.ID, Question: question, Options: string(raw), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane}
+ c := cardRecord{ProjectID: r.ProjectID, ID: newID("c_"), Person: r.Person, Kind: wire.CardQuestion, State: wire.CardOpen, TurnID: r.ID, Question: question, Options: string(raw), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane}
if err := t.db.Create(&c).Error; err != nil {
return wire.ToolResult{}, err
}
diff --git a/internal/equipo/chat_days.go b/internal/equipo/chat_days.go
index dc73a22f..f8462535 100644
--- a/internal/equipo/chat_days.go
+++ b/internal/equipo/chat_days.go
@@ -345,7 +345,7 @@ func feedLines(msgs []wire.Message, cards []wire.Card, choices []string, tasks m
var out []chatLine
last := map[string]int{}
for i, m := range msgs {
- out = append(out, chatLine{ID: m.ID, Text: m.Text, TurnID: m.TurnID, Own: m.Role == wire.RolePerson, CreatedAt: m.CreatedAt, Switched: switchedText(m.Switched), Files: m.Attachments})
+ out = append(out, chatLine{ProjectID: m.ProjectID, ID: m.ID, Text: m.Text, TurnID: m.TurnID, Own: m.Role == wire.RolePerson, CreatedAt: m.CreatedAt, Switched: switchedText(m.Switched), Files: m.Attachments})
last[m.TurnID] = i
}
reply := map[string]int{}
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index 4985260b..11d98380 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -23,7 +23,8 @@ import (
type chatView struct {
// Draft is the composer's opening words: "Ask about this" on a task
// opens the conversation with the task referenced (?about=tk...).
- Draft string
+ Draft string
+ Projects []wire.Project
// Messages are today's; Days the earlier days, oldest first; Open what
// still needs the person from them, at the top of today.
Messages []chatLine
@@ -50,6 +51,7 @@ type chatLine struct {
// behind the running one (no thinking line, no timer).
Queued string
ID, Text, TurnID string
+ ProjectID string
// Files are what the person attached to their message.
Files []wire.MessageAttachment
Own bool
@@ -249,7 +251,7 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
a.failure(w, r, err)
return
}
- view := chatView{Offline: !snap.Runner.Online, Cursor: snap.Cursor}
+ view := chatView{Offline: !snap.Runner.Online, Cursor: snap.Cursor, Projects: snap.Projects}
if id := r.URL.Query().Get("about"); taskIDPattern.MatchString(id) {
// A task the person cannot see, or none, leaves the composer empty.
if t, err := a.store.Chat().Task(ctx, address, id); err == nil {
@@ -380,7 +382,7 @@ func (a *application) chatSend(w http.ResponseWriter, r *http.Request) {
a.failure(w, r, ErrForbidden)
return
}
- in := wire.SendMessage{Text: r.PostFormValue("body"), IdempotencyKey: r.PostFormValue("request_id")}
+ in := wire.SendMessage{ProjectID: r.PostFormValue("project_id"), Text: r.PostFormValue("body"), IdempotencyKey: r.PostFormValue("request_id")}
if r.PostForm != nil {
in.Attachments = r.PostForm["attachment"]
}
diff --git a/internal/equipo/migrations/0081_project_threads.sql b/internal/equipo/migrations/0081_project_threads.sql
new file mode 100644
index 00000000..d2600a74
--- /dev/null
+++ b/internal/equipo/migrations/0081_project_threads.sql
@@ -0,0 +1,3 @@
+-- Explicit scope only: old ambiguous conversation remains General.
+ALTER TABLE chat_messages ADD COLUMN project_id text;
+ALTER TABLE chat_turns ADD COLUMN project_id text;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 4beedc9a..828d8d41 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -571,9 +571,9 @@ ALTER TABLE coordinator_turns ADD COLUMN partial_at integer;
ALTER TABLE coordinator_turns ADD COLUMN reply_message_id text;
ALTER TABLE coordinator_turns ADD COLUMN superseded_by text;
-CREATE TABLE chat_turns (id text PRIMARY KEY, person text, state text, reason text, attempt integer, dispatched numeric, reply_id text, revision integer, created_at datetime, updated_at datetime, dispatched_at datetime, timing text, kind text, yield numeric, connection text, lane text, note text);
+CREATE TABLE chat_turns (id text PRIMARY KEY, person text, state text, reason text, attempt integer, dispatched numeric, reply_id text, revision integer, created_at datetime, updated_at datetime, dispatched_at datetime, timing text, kind text, yield numeric, connection text, lane text, note text, project_id text);
CREATE INDEX chat_turn_person ON chat_turns(person,state);
-CREATE TABLE chat_messages (seq integer PRIMARY KEY, id text, person text, idempotency_key text, body_hash text, role text, text text, turn_id text, revision integer, created_at datetime, switched text, lane text);
+CREATE TABLE chat_messages (seq integer PRIMARY KEY, id text, person text, idempotency_key text, body_hash text, role text, text text, turn_id text, revision integer, created_at datetime, switched text, lane text, project_id text);
CREATE UNIQUE INDEX chat_message_id ON chat_messages(id);
CREATE INDEX chat_message_person ON chat_messages(person);
CREATE UNIQUE INDEX chat_message_key ON chat_messages(person,lane,idempotency_key);
diff --git a/internal/equipo/static/chat-anchor.js b/internal/equipo/static/chat-anchor.js
index a6bc5ba8..56e4f064 100644
--- a/internal/equipo/static/chat-anchor.js
+++ b/internal/equipo/static/chat-anchor.js
@@ -10,6 +10,7 @@
function show() {
var el = [].find.call(document.querySelectorAll("[data-message]"), function (e) { return e.getAttribute("data-message") === id; });
if (!el) return;
+ for (var parent = el.parentElement; parent; parent = parent.parentElement) { if (parent.tagName === "DETAILS") parent.open = true; }
var scroll = el.closest("[equipo-scroll]");
if (scroll) {
scroll.scrollTop += el.getBoundingClientRect().top - scroll.getBoundingClientRect().top - Math.max(0, (scroll.clientHeight - el.offsetHeight) / 2);
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js
index c9c2617a..0741f3d4 100644
--- a/internal/equipo/static/chat-stream.js
+++ b/internal/equipo/static/chat-stream.js
@@ -798,6 +798,7 @@
if (more) more.setAttribute("aria-expanded", "true");
});
feed.querySelectorAll("[data-message]").forEach(function (el) { shown[el.dataset.message] = true; });
+ if (window.EquipoProjectThreads) window.EquipoProjectThreads.beforeRefresh(doc);
feed.replaceChildren.apply(feed, Array.from(next.children).map(function (el) {
var fresh = el.matches('[equipo-message="incoming"][data-turn-id]') && !shown[el.dataset.message];
var turn = el.hasAttribute("equipo-thinking") ? el.dataset.turn : fresh ? el.dataset.turnId : "";
@@ -849,6 +850,7 @@
if (e.cursor <= cursor) return;
cursor = e.cursor;
var v = e.data;
+ if (window.EquipoProjectThreads && type === "turn") window.EquipoProjectThreads.turn(v.id, v.project_id);
if (type === "turn" || type === "message" || type === "card" || type === "task" || type === "step") shape = cursor;
if (type === "thinking") {
root.dataset.thinkingSet = v.set;
@@ -904,21 +906,23 @@
}
// A send from this page still waiting for its answer: the event
// names it in place, so the messages keep the order they were sent.
- var mine = Array.from(local).find(function (el) { return !el.dataset.message && el.isConnected && el.querySelector("[equipo-message-body]").textContent === v.text; });
+ var mine = Array.from(local).find(function (el) { return !el.dataset.message && el.isConnected && el.querySelector("[equipo-message-body]").textContent === v.text && (el.dataset.projectId || "") === (v.project_id || ""); });
if (mine) {
+ mine.dataset.projectId = v.project_id || "";
mine.dataset.message = v.id;
mine.dataset.turnId = v.turn_id || "";
notes();
return;
}
var own = template("equipo-own-template");
+ own.dataset.projectId = v.project_id || "";
own.dataset.message = v.id;
own.dataset.turnId = v.turn_id || "";
own.querySelector("[equipo-message-body]").textContent = v.text;
sentFiles(own, served(v.attachments));
own.querySelector("time").textContent = new Date(v.created_at).toTimeString().slice(0, 5);
var waiting = feed.querySelector("[equipo-thinking]");
- feed.insertBefore(own, waiting);
+ feed.insertBefore(own, waiting && waiting.parentNode === feed ? waiting : null);
notes();
scroll();
} else if (type === "turn") {
@@ -1057,7 +1061,8 @@
}
function place(el) {
clearEmpty();
- feed.insertBefore(el, feed.querySelector("[equipo-thinking]"));
+ var waiting = feed.querySelector("[equipo-thinking]");
+ feed.insertBefore(el, waiting && waiting.parentNode === feed ? waiting : null);
scroll();
}
// served is a message's attachments as the server keeps them.
@@ -1176,6 +1181,8 @@
input.focus();
var el = template("equipo-own-template");
el.dataset.message = "";
+ var project = form.querySelector("[name=project_id]");
+ el.dataset.projectId = project ? project.value : "";
el.querySelector("[equipo-message-body]").textContent = text;
el.querySelector("time").textContent = new Date().toTimeString().slice(0, 5);
// The attachments show at once, from this device's copies.
@@ -1186,6 +1193,7 @@
// The coordinator's line, now: nothing waits on the network. Sent
// while a turn runs, the message waits its turn: the note instead.
var line = lineOrNote(el, who);
+ if (line) line.dataset.projectId = el.dataset.projectId || "";
scroll(true);
// The form's other fields as they are now (who a question is for).
var extra = {};
diff --git a/internal/equipo/static/equipo.css b/internal/equipo/static/equipo.css
index 2e2f0135..62048302 100644
--- a/internal/equipo/static/equipo.css
+++ b/internal/equipo/static/equipo.css
@@ -1763,3 +1763,15 @@ label[equipo-sp-label] { cursor: pointer; }
[equipo-day-row]:first-child dt { margin-block-start: 0; }
}
@media (prefers-reduced-motion: reduce) { [equipo-day-toggle] .icon { transition: none; } }
+
+/* Project subthreads keep action forms out of the overview. */
+[data-project-thread] { list-style: none; border: 1px solid color-mix(in srgb, currentColor 18%, transparent); border-radius: 12px; margin-block: 10px; }
+[data-project-thread] > details > summary { cursor: pointer; padding: 16px; }
+[data-project-thread] summary strong { margin-inline: 8px; }
+[data-project-thread] summary span { font-size: .85em; opacity: .75; }
+[data-project-messages] { display: flex; flex-direction: column; gap: var(--rst-sp-4); list-style: none; padding: 12px; margin: 0; }
+[data-project-thread] > details > button { margin: 12px; }
+[data-project-thread] #chat-composer { position: static; padding: 12px; }
+[data-composer-scope] { font-size: .85em; margin: 4px 12px; }
+
+[data-project-thread] #chat-composer::before { display: none; }
diff --git a/internal/equipo/static/project-threads.js b/internal/equipo/static/project-threads.js
new file mode 100644
index 00000000..e17ace63
--- /dev/null
+++ b/internal/equipo/static/project-threads.js
@@ -0,0 +1,127 @@
+// A presentation of one conversation, not independent sessions. Only explicit
+// message scope and card project links are used. Unknown history stays General.
+(function () {
+ "use strict";
+ var catalog = document.querySelector('[data-project-catalog]');
+ if (!catalog) return;
+ var root = document.querySelector('[data-chat-stream]');
+ var feed = root.querySelector('[equipo-feed]');
+ var composer = document.getElementById('chat-composer');
+ var home = composer.parentNode;
+ var input = composer.querySelector('[name=project_id]');
+ var groups = {}, turns = {}, opened = {}, seen = {};
+ var docked = null, focus = null;
+ var known = {};
+ try { seen = JSON.parse(sessionStorage.getItem('equipo:project-reads') || '{}'); } catch (_) {}
+ function readKey(n) { return (n.dataset.message || n.dataset.card) + ':' + (n.dataset.state || ''); }
+ function catalogue(node) {
+ node.querySelectorAll('[data-project-id]').forEach(function (p) {
+ known[p.dataset.projectId] = {name: p.dataset.name, status: p.dataset.status};
+ });
+ }
+ catalogue(catalog);
+ function scope(id) {
+ input.value = id;
+ composer.querySelector('[data-composer-scope]').textContent = id ? 'Message to ' + known[id].name : 'General conversation';
+ composer.querySelector('textarea').setAttribute('aria-label', id ? 'Message to ' + known[id].name : 'General conversation');
+ }
+ function group(id) {
+ if (groups[id] && groups[id].box.isConnected) return groups[id];
+ var li = document.createElement('li'), details = document.createElement('details');
+ li.setAttribute('data-project-thread', id);
+ var summary = document.createElement('summary'), title = document.createElement('strong'), status = document.createElement('span');
+ title.textContent = id ? known[id].name : 'General conversation';
+ summary.append(title, status);
+ var list = document.createElement('ol');
+ list.setAttribute('data-project-messages', id);
+ var button = document.createElement('button');
+ button.type = 'button';
+ button.setAttribute('rst-btn', '');
+ button.textContent = id ? 'Message this project' : 'Message General';
+ button.addEventListener('click', function () {
+ // A draft and its uploads must never silently change destination.
+ if (input.value !== id && (composer.querySelector('textarea').value.trim() || (window.EquipoAttach && window.EquipoAttach.count()))) {
+ composer.querySelector('[data-composer-scope]').textContent += ' · Send or clear this draft before switching projects.';
+ return;
+ }
+ scope(id);
+ docked = id;
+ details.append(composer);
+ composer.querySelector('textarea').focus();
+ });
+ details.append(summary, list, button);
+ details.open = id === '' ? opened[id] !== false : !!opened[id];
+ details.addEventListener('toggle', function () {
+ opened[id] = details.open;
+ if (details.open) markRead(id);
+ if (!details.open && details.contains(composer)) { docked = null; home.append(composer); }
+ update(id);
+ });
+ li.append(details);
+ feed.append(li);
+ groups[id] = {box: li, details: details, list: list, status: status};
+ return groups[id];
+ }
+ function markRead(id) {
+ var g = groups[id];
+ g.list.querySelectorAll('[data-message], [data-card]').forEach(function (n) {
+ seen[readKey(n)] = true;
+ });
+ try { sessionStorage.setItem('equipo:project-reads', JSON.stringify(seen)); } catch (_) {}
+ }
+ function update(id) {
+ var g = groups[id], needs = g.list.querySelectorAll('[data-needs-you="true"]').length;
+ var unread = Array.from(g.list.querySelectorAll('[data-message], [data-card]')).filter(function (n) { return !seen[readKey(n)]; }).length;
+ g.status.textContent = [id ? known[id].status : 'Cross-project requests and unassigned history', needs ? needs + ' needs you' : '', unread ? unread + ' unread' : ''].filter(Boolean).join(' · ');
+ }
+ function arrange() {
+ observer.disconnect();
+ group('');
+ Object.keys(known).forEach(group);
+ feed.querySelectorAll('[data-project-id][data-turn-id], [data-project-id][data-turn]').forEach(function (n) {
+ var turn = n.dataset.turnId || n.dataset.turn;
+ if (turn && n.dataset.projectId && !n.hasAttribute('data-card')) turns[turn] = n.dataset.projectId;
+ });
+ // Keep General's day navigation and history in their original order.
+ Array.from(feed.children).forEach(function (n) {
+ if (!n.hasAttribute('data-project-thread')) groups[''].list.append(n);
+ });
+ // Snapshot the nodes before moving them, preserving their order within
+ // each project, including cards before/after the reply that produced them.
+ Array.from(feed.querySelectorAll('[data-message], [data-card], [equipo-thinking], [data-ended]')).forEach(function (n) {
+ var id = n.dataset.projectId || (!n.hasAttribute('data-card') && turns[n.dataset.turnId || n.dataset.turn]) || '';
+ if (!known[id]) id = '';
+ var g = group(id);
+ if (id === '' && g.list.contains(n)) return;
+ if (n.parentNode !== g.list) g.list.append(n);
+ });
+ Object.keys(groups).forEach(function (id) {
+ if (groups[id].details.open) markRead(id);
+ update(id);
+ });
+ if (docked !== null && groups[docked] && groups[docked].details.open && composer.parentNode !== groups[docked].details) groups[docked].details.append(composer);
+ if (focus) {
+ focus.node.focus({preventScroll: true});
+ if (focus.start !== null) focus.node.setSelectionRange(focus.start, focus.end);
+ focus = null;
+ }
+ observer.observe(feed, {childList: true, subtree: true, attributes: true, attributeFilter: ['data-project-id', 'data-turn', 'data-turn-id', 'data-message']});
+ }
+ var observer = new MutationObserver(arrange);
+ // Refresh replaces the flat server feed. Save the single attachment-aware
+ // composer first; the grouping pass then adopts the new nodes, never copies.
+ window.EquipoProjectThreads = {
+ beforeRefresh: function (doc) {
+ if (feed.contains(composer)) {
+ var active = document.activeElement;
+ if (composer.contains(active)) focus = {node: active, start: typeof active.selectionStart === 'number' ? active.selectionStart : null, end: active.selectionEnd};
+ home.append(composer);
+ }
+ var next = doc.querySelector('[data-project-catalog]');
+ if (next) catalogue(next);
+ },
+ turn: function (id, project) { if (project) turns[id] = project; },
+ arrange: arrange
+ };
+ arrange();
+})();
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html
index aecff5a9..92d27b2d 100644
--- a/internal/equipo/templates/chat.html
+++ b/internal/equipo/templates/chat.html
@@ -1,6 +1,6 @@
{{define "up-label"}}{{copy "nav.work"}}{{end}}
{{define "title"}}{{copy "conversation.title"}}{{end}}
-{{define "chat-card"}}<li equipo-card="{{.Kind}}"{{if .Receipt}} equipo-receipt{{end}} data-card="{{.ID}}" data-state="{{.State}}" data-turn-id="{{.TurnID}}">
+{{define "chat-card"}}<li equipo-card="{{.Kind}}"{{if .Receipt}} equipo-receipt{{end}} data-project-id="{{.ProjectID}}" data-needs-you="{{if .Receipt}}{{if .Task}}{{if .Task.NeedsYou}}true{{else}}false{{end}}{{else}}false{{end}}{{else}}{{.Open}}{{end}}" data-card="{{.ID}}" data-state="{{.State}}" data-turn-id="{{.TurnID}}">
{{if and .Receipt (eq .Kind "task")}}{{template "work-task-receipt" .}}
{{else if eq .Kind "advice"}}{{if ne .State "resolved"}}<p equipo-card-line data-advice-card>{{icon "lightbulb"}}<span>{{.Line}}</span></p>{{if .Open}}<form method="post" action="/conversation/cards/{{.ID}}/answer" data-card-form equipo-actions><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn="primary" name="choice" value="act" type="submit" data-advice-choice="act">{{.ActLabel}}</button><button rst-btn name="choice" value="dismiss" type="submit" data-advice-choice="dismiss">{{.DismissLabel}}</button></form>{{else}}{{with .Note}}<p equipo-card-note>{{.}}</p>{{end}}{{end}}{{end}}
{{else if eq .Kind "housekeeping"}}<p equipo-card-line data-digest>{{icon "list-checks"}}<span>{{.Line}} <a href="/housekeeping" data-digest-link>{{copy "chat.housekeeping.link"}}</a></span></p>
@@ -21,7 +21,7 @@
{{define "chat-lines"}}{{$address := .Address}}{{range .Lines}}
{{if .CardOnly}}{{range .Cards}}{{template "chat-card" .}}{{end}}{{else}}
{{range .Receipts}}{{template "chat-card" .}}{{end}}
-<li equipo-message="{{if .Own}}own{{else}}incoming{{end}}" data-message="{{.ID}}" data-turn-id="{{.TurnID}}">
+<li equipo-message="{{if .Own}}own{{else}}incoming{{end}}" data-project-id="{{.ProjectID}}" data-message="{{.ID}}" data-turn-id="{{.TurnID}}">
<div equipo-message-meta><strong{{if .Own}} equipo-visually-hidden{{end}}>{{if .Own}}{{$address}}{{else}}{{icon "message-circle"}}{{copy "conversation.coordinator"}}{{end}}</strong><time datetime="{{.CreatedAt.Format "2006-01-02T15:04:05Z07:00"}}">{{.CreatedAt.Format "15:04"}}</time></div>
{{if .Own}}{{template "message-files" .Files}}{{end}}<div equipo-bubble>{{if .Own}}<p equipo-message-body>{{.Text}}</p>{{else}}<div equipo-message-body equipo-markdown>{{chatMarkdown .Text}}</div>{{end}}</div>
{{with .Waiting}}<p equipo-card-note data-waiting-connection>{{.}}</p>{{end}}
@@ -50,6 +50,7 @@
<template equipo-chip-template><li equipo-chip data-state="uploading"><span equipo-chip-thumb>{{icon "file-text"}}</span><span equipo-chip-text><span equipo-chip-name></span><span equipo-chip-note></span></span><span equipo-chip-progress role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><i></i></span><button type="button" equipo-chip-remove>{{icon "x"}}</button></li></template>
<template equipo-thinking-template><li equipo-message="incoming" equipo-thinking data-turn="" data-started="" aria-busy="true"><div equipo-message-meta><strong>{{icon "message-circle"}}{{copy "conversation.coordinator"}}</strong><time></time></div><div equipo-bubble><div equipo-message-body equipo-markdown data-stream-text></div><p equipo-activity-line><span equipo-activity>{{copy "chat.activity.thinking"}}</span><span equipo-activity-sep aria-hidden="true">·</span><span equipo-elapsed></span></p></div></li></template>
<template equipo-ended-template><li equipo-system-note data-ended=""><p></p></li></template>
+<div data-project-catalog hidden>{{range .Chat.Projects}}<span data-project-id="{{.ID}}" data-name="{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}" data-status="{{.State}}"></span>{{end}}</div>
<ol equipo-feed>
{{range .Chat.Days}}{{template "chat-day" .}}{{end}}
{{if .Chat.Days}}<li equipo-day-divider data-today><span>{{copy "chat.day.today"}}</span></li>{{end}}
@@ -57,15 +58,16 @@
{{template "chat-lines" (.Chat.Earlier .Address)}}
{{template "chat-lines" (.Chat.Today .Address)}}
{{if not (or .Chat.Days .Chat.Open .Chat.Messages)}}<li data-empty-state="conversation.empty">{{copy "conversation.empty"}}</li>{{end}}
-{{range .Chat.Waiting}}<li equipo-message="incoming" equipo-thinking data-turn="{{.ID}}"{{with .Kind}} data-kind="{{.}}"{{end}} data-started="{{.CreatedAt.UnixMilli}}" aria-busy="true"><div equipo-message-meta><strong>{{icon "message-circle"}}{{copy "conversation.coordinator"}}</strong><time></time></div><div equipo-bubble><div equipo-message-body equipo-markdown data-stream-text></div><p equipo-activity-line><span equipo-activity>{{if eq .Kind "move_in"}}{{copy "chat.moving_in"}}{{else if eq .Kind "explore"}}{{copy "chat.exploring"}}{{else}}{{copy "chat.activity.thinking"}}{{end}}</span><span equipo-activity-sep aria-hidden="true">·</span><span equipo-elapsed></span></p></div></li>{{end}}
+{{range .Chat.Waiting}}<li equipo-message="incoming" equipo-thinking data-project-id="{{.ProjectID}}" data-turn="{{.ID}}"{{with .Kind}} data-kind="{{.}}"{{end}} data-started="{{.CreatedAt.UnixMilli}}" aria-busy="true"><div equipo-message-meta><strong>{{icon "message-circle"}}{{copy "conversation.coordinator"}}</strong><time></time></div><div equipo-bubble><div equipo-message-body equipo-markdown data-stream-text></div><p equipo-activity-line><span equipo-activity>{{if eq .Kind "move_in"}}{{copy "chat.moving_in"}}{{else if eq .Kind "explore"}}{{copy "chat.exploring"}}{{else}}{{copy "chat.activity.thinking"}}{{end}}</span><span equipo-activity-sep aria-hidden="true">·</span><span equipo-elapsed></span></p></div></li>{{end}}
{{with .Chat.NoConnection}}<li equipo-card="no_connection" data-no-connection="{{.TurnID}}"><p equipo-card-line>{{.Line}}</p><p equipo-actions><a rst-btn="primary" href="/conversation/settings/connections/add" data-add-connection>{{copy "chat.no_connection.add"}}</a></p></li>{{end}}
{{with .Chat.Ended}}<li equipo-system-note data-ended="{{.ID}}"><p>{{copy .Key}}</p></li>{{end}}
</ol>
</section>
</div>
<div equipo-announcements role="status" aria-live="polite" aria-atomic="false"></div>
-<div id="chat-composer">
+<div id="chat-composer"><p data-composer-scope>General conversation</p>
<form id="composer" equipo-form equipo-composer method="post" action="/conversation" data-failed="{{copy "chat.failed"}}" data-failed-many="{{copy "chat.failed_many"}}" data-failed-storage="{{copy "chat.failed_storage"}}" data-retry="{{copy "conversation.retry"}}" data-cancelled="{{copy "chat.cancelled"}}" data-upload="/conversation/attachments" data-max-files="5" data-max-bytes="10485760" data-too-large="{{copy "api.attachment_too_large"}}" data-heic="{{copy "api.attachment_heic"}}" data-too-many="{{copy "chat.attach.too_many"}}" data-upload-failed="{{copy "chat.attach.failed"}}" data-uploading="{{copy "chat.attach.uploading"}}" data-remove="{{copy "chat.attach.remove"}}">
+<input type="hidden" name="project_id" value="">
<input type="hidden" name="request_id" value="{{.RequestID}}">
<div equipo-adder hidden><button type="button" equipo-plus aria-label="{{copy "chat.attach.add"}}" title="{{copy "chat.attach.add"}}" aria-haspopup="menu" aria-expanded="false" aria-controls="attach-menu">{{icon "plus"}}</button><div equipo-add-menu id="attach-menu" role="menu" aria-label="{{copy "chat.attach.add"}}" hidden><button type="button" role="menuitem" data-pick="image">{{icon "image"}}<span>{{copy "chat.attach.image"}}</span></button><button type="button" role="menuitem" data-pick="file">{{icon "file-text"}}<span>{{copy "chat.attach.file"}}</span></button></div><input type="file" data-picker="image" accept="image/*" multiple tabindex="-1" aria-hidden="true" equipo-visually-hidden><input type="file" data-picker="file" accept=".txt,.md,.markdown,.csv,.json,.log,.pdf,text/plain,text/markdown,text/csv,application/json,application/pdf" multiple tabindex="-1" aria-hidden="true" equipo-visually-hidden></div>
<div equipo-pill>
diff --git a/internal/equipo/templates/chrome.html b/internal/equipo/templates/chrome.html
index f31baf5d..fe3ef233 100644
--- a/internal/equipo/templates/chrome.html
+++ b/internal/equipo/templates/chrome.html
@@ -1,6 +1,6 @@
{{define "rail-brand"}}<span hidden></span>{{end}}
{{define "title"}}{{copy .Title}} · {{copy "brand"}}{{end}}
-{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}"><script defer src="{{asset "static/nav-stream.js"}}"></script><script defer src="{{asset "static/work-stream.js"}}"></script><script defer src="{{asset "static/stardust.js"}}"></script><script defer src="{{asset "static/team-panel.js"}}"></script><script defer src="{{asset "static/paste.js"}}"></script>{{with .Thin.MergePolicy}}{{if .Editable}}<script defer src="{{asset "static/merge-ships.js"}}"></script>{{end}}{{end}}{{if .HousekeepingStream}}<script defer src="{{asset "static/housekeeping.js"}}"></script>{{end}}{{if or (eq .Key "thinking") (eq .Key "settings-hub")}}<script defer src="{{asset "static/thinking-preview.js"}}"></script><script defer src="{{asset "static/settings.js"}}"></script>{{end}}{{if .ConnectionsStream}}<script defer src="{{asset "static/vendor/tweetnacl/nacl-fast.js"}}"></script><script defer src="{{asset "static/seal.js"}}"></script><script defer src="{{asset "static/connections.js"}}"></script>{{end}}{{if .MachinesStream}}<script defer src="{{asset "static/machines.js"}}"></script>{{end}}{{if .ChatStream}}<script defer src="{{asset "static/chat-stream.js"}}"></script><script defer src="{{asset "static/chat-compose.js"}}"></script><script defer src="{{asset "static/ask-target.js"}}"></script>{{if eq .Key "conversation"}}<script defer src="{{asset "static/chat-anchor.js"}}"></script><script defer src="{{asset "static/chat-attach.js"}}"></script>{{end}}{{else if eq .Key "conversation"}}<script defer blocking="render" src="{{asset "static/chat-navigation.js"}}"></script><script defer src="{{asset "static/chat.js"}}"></script><script defer src="{{asset "static/chat-send.js"}}"></script>{{end}}{{end}}
+{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}"><script defer src="{{asset "static/nav-stream.js"}}"></script><script defer src="{{asset "static/work-stream.js"}}"></script><script defer src="{{asset "static/stardust.js"}}"></script><script defer src="{{asset "static/team-panel.js"}}"></script><script defer src="{{asset "static/paste.js"}}"></script>{{with .Thin.MergePolicy}}{{if .Editable}}<script defer src="{{asset "static/merge-ships.js"}}"></script>{{end}}{{end}}{{if .HousekeepingStream}}<script defer src="{{asset "static/housekeeping.js"}}"></script>{{end}}{{if or (eq .Key "thinking") (eq .Key "settings-hub")}}<script defer src="{{asset "static/thinking-preview.js"}}"></script><script defer src="{{asset "static/settings.js"}}"></script>{{end}}{{if .ConnectionsStream}}<script defer src="{{asset "static/vendor/tweetnacl/nacl-fast.js"}}"></script><script defer src="{{asset "static/seal.js"}}"></script><script defer src="{{asset "static/connections.js"}}"></script>{{end}}{{if .MachinesStream}}<script defer src="{{asset "static/machines.js"}}"></script>{{end}}{{if .ChatStream}}<script defer src="{{asset "static/chat-stream.js"}}"></script><script defer src="{{asset "static/chat-compose.js"}}"></script><script defer src="{{asset "static/ask-target.js"}}"></script>{{if eq .Key "conversation"}}<script defer src="{{asset "static/project-threads.js"}}"></script><script defer src="{{asset "static/chat-anchor.js"}}"></script><script defer src="{{asset "static/chat-attach.js"}}"></script>{{end}}{{else if eq .Key "conversation"}}<script defer blocking="render" src="{{asset "static/chat-navigation.js"}}"></script><script defer src="{{asset "static/chat.js"}}"></script><script defer src="{{asset "static/chat-send.js"}}"></script>{{end}}{{end}}
{{define "up"}}/work{{if .Key}}#nav-{{.Key}}{{end}}{{end}}
{{define "up-label"}}{{.TeamName}}{{end}}
{{define "brand"}}<a rst-shell-brand href="/work">{{icon "users"}}{{.TeamName}}</a>{{end}}
diff --git a/internal/headless/browser_project_threads_test.go b/internal/headless/browser_project_threads_test.go
new file mode 100644
index 00000000..169a3c86
--- /dev/null
+++ b/internal/headless/browser_project_threads_test.go
@@ -0,0 +1,44 @@
+//go:build browser
+
+package headless
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/browsertest"
+ "amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/chromedp"
+)
+
+// The presentation contract uses the production script, independent of a
+// model or runner. Persistent send scope is covered by the store contract.
+func TestBrowserProjectThreads(t *testing.T) {
+ root, err := filepath.Abs("../../release/project-threads")
+ if err != nil {
+ t.Fatal(err)
+ }
+ script, err := filepath.Abs("../equipo/static/project-threads.js")
+ if err != nil {
+ t.Fatal(err)
+ }
+ mux := http.NewServeMux()
+ mux.HandleFunc("/project-threads.js", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, script) })
+ mux.Handle("/", http.FileServer(http.Dir(root)))
+ server := httptest.NewServer(mux)
+ defer server.Close()
+ alloc, stop := chromedp.NewExecAllocator(context.Background(), append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox)...)
+ defer stop()
+ ctx, cancel := chromedp.NewContext(alloc)
+ defer cancel()
+ if err := chromedp.Do(ctx, chromedp.Navigate(server.URL+"/?test=1"), browsertest.Wait(`document.querySelector('#test-result').textContent.startsWith('PASS:')`)); err != nil {
+ t.Fatal(err)
+ }
+ // A real document reload restores the closed-by-default overview.
+ if err := chromedp.Do(ctx, chromedp.Navigate(server.URL), browsertest.Wait(`document.querySelectorAll('[data-project-thread]').length===3 && !document.querySelector('[data-project-thread="p1"] details').open && !document.querySelector('[data-project-thread="p2"] details').open`)); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/wire/api.go b/internal/wire/api.go
index e57b7537..4019cfbf 100644
--- a/internal/wire/api.go
+++ b/internal/wire/api.go
@@ -159,6 +159,7 @@ type Person struct {
// Message is one line of the person's conversation.
type Message struct {
+ ProjectID string `json:"project_id,omitempty"`
ID string `json:"id"`
Revision int64 `json:"revision"`
Role string `json:"role"`
@@ -202,6 +203,7 @@ const (
// Turn is one coordinator answer to one or more queued person messages,
// or a turn the coordinator takes on its own (Kind move_in or explore).
type Turn struct {
+ ProjectID string `json:"project_id,omitempty"`
ID string `json:"id"`
Revision int64 `json:"revision"`
Kind string `json:"kind"`
@@ -432,6 +434,7 @@ type Snapshot struct {
// SendMessage is the body of POST /api/v1/messages.
type SendMessage struct {
+ ProjectID string `json:"project_id,omitempty"`
Text string `json:"text"`
IdempotencyKey string `json:"idempotency_key"`
// Attachments are ids from POST /api/v1/attachments, the sender's own
diff --git a/release/preview.json b/release/preview.json
new file mode 100644
index 00000000..c7cae3c0
--- /dev/null
+++ b/release/preview.json
@@ -0,0 +1 @@
+{"output":"release/project-threads"}
diff --git a/release/project-threads/README.md b/release/project-threads/README.md
new file mode 100644
index 00000000..a25c3e1f
--- /dev/null
+++ b/release/project-threads/README.md
@@ -0,0 +1,32 @@
+# Project conversation review
+
+This is a plain static interactive preview with sample content. `project-threads.js`
+is a copy of the production grouping script. It does not submit real prompts or
+perform task actions. Open `index.html` to review the closed overview and expanded
+project layout. Open `index.html?test=1` to run the browser presentation assertions.
+The browser-tagged Go test serves this fixture with the actual production script.
+
+Implementation notes:
+- Explicit message and turn scope is stored durably. Existing ambiguous messages
+ stay in General; existing cards use their established project association.
+- One attachment-aware composer moves into the selected project. Drafts cannot
+ silently change destination. Projects close on document reload; in-page live
+ refreshes preserve their open state. Read indicators persist within the tab.
+- Existing day navigation remains in General. Opening an older day distributes
+ its explicitly scoped messages into the relevant project groups.
+- This is a presentation grouping, not separate coordinator sessions or queues.
+
+Validation in this environment:
+- JavaScript syntax checks passed.
+- Go tests could not run: dependencies were unavailable and network escalation
+ was denied.
+- Headless Chromium could not start because sandbox socket access was denied;
+ escalation was also denied. No screenshot or passing browser run is claimed.
+
+Suggested CI checks:
+`go test ./internal/equipo/chat ./internal/equipo`
+`go test -tags browser ./internal/headless -run TestBrowserProjectThreads`
+
+Review should include a connected-runner check of streamed replies, attachments,
+card actions and older-day navigation. The static browser fixture tests grouping
+and DOM refresh, not the full live event transport.
diff --git a/release/project-threads/browser-test.js b/release/project-threads/browser-test.js
new file mode 100644
index 00000000..43246c8f
--- /dev/null
+++ b/release/project-threads/browser-test.js
@@ -0,0 +1,36 @@
+// Open ?test=1 in a browser to exercise the production grouping script.
+(async function () {
+ if (!new URLSearchParams(location.search).has('test')) return;
+ const wait = () => new Promise(resolve => setTimeout(resolve, 40));
+ const check = (value, reason) => { if (!value) throw new Error(reason); };
+ const project = id => document.querySelector('[data-project-thread="'+id+'"]');
+ try {
+ await wait();
+ check(!project('p1').querySelector('details').open && !project('p2').querySelector('details').open, 'projects start closed');
+ check(project('p1').querySelector('summary').textContent.includes('needs you'), 'collapsed needs-you indicator');
+ check(project('p1').querySelector('[data-card] button').getClientRects().length === 0, 'collapsed actions are hidden');
+ check(project('').querySelector('[data-message="general"]'), 'ambiguous history stays General');
+ project('p1').querySelector('details').open = true;
+ project('p1').querySelector('details > button').click();
+ check(document.querySelector('[name=project_id]').value === 'p1', 'composer explicitly scoped');
+ check(project('p1').contains(document.getElementById('chat-composer')), 'composer inside project');
+ check(!project('p1').querySelector('[data-message="three"]'), 'no unrelated messages');
+ document.querySelector('#composer textarea').value = 'Keep this draft here';
+ project('p2').querySelector('details > button').click();
+ check(document.querySelector('[name=project_id]').value === 'p1', 'draft cannot change destination');
+ const feed = document.querySelector('[equipo-feed]');
+ const update = document.createElement('li');
+ update.dataset.message = 'live'; update.dataset.projectId = 'p2'; update.textContent = 'Live update'; feed.append(update);
+ await wait();
+ check(project('p2').querySelector('[data-message="live"]'), 'live update routes to closed project');
+ check(!project('p2').querySelector('details').open, 'live event does not expand project');
+ check(document.querySelectorAll('[data-message="live"]').length === 1, 'live update is not duplicated');
+ const next = new DOMParser().parseFromString('<div data-project-catalog></div>', 'text/html');
+ window.EquipoProjectThreads.beforeRefresh(next);
+ feed.innerHTML = '<li data-message="reloaded" data-project-id="p1">Persisted scope</li>';
+ await wait();
+ check(project('p1').querySelector('[data-message="reloaded"]'), 'snapshot refresh retains attribution');
+ check(document.querySelector('#composer textarea').value === 'Keep this draft here', 'refresh preserves draft');
+ document.getElementById('test-result').textContent = 'PASS: project thread browser checks';
+ } catch (e) { document.getElementById('test-result').textContent = 'FAIL: ' + e.message; throw e; }
+})();
diff --git a/release/project-threads/index.html b/release/project-threads/index.html
new file mode 100644
index 00000000..cf6feb12
--- /dev/null
+++ b/release/project-threads/index.html
@@ -0,0 +1,16 @@
+<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Project conversation preview</title>
+<style>
+body{font:16px system-ui;background:#f8f8f6;color:#242b32;margin:0}main{max-width:880px;margin:48px auto;padding:24px}h1{font-size:26px}p{line-height:1.5}.hint{color:#63707b;font-size:14px}ol{list-style:none;padding:0}li[data-project-thread]{background:white;border:1px solid #d9dfe2;border-radius:12px;margin:12px 0}summary{cursor:pointer;padding:20px}summary strong{margin:0 10px}summary span{color:#687780;font-size:13px}[data-project-messages]{padding:0 24px}[data-project-messages]>li{padding:16px 0;border-bottom:1px solid #eee}button{border:1px solid #bbc8d0;border-radius:8px;background:white;padding:10px 16px;cursor:pointer}details>button{margin:16px 24px}textarea{width:90%;min-height:70px;border:1px solid #bbc8d0;border-radius:10px;padding:12px;font:inherit}#chat-composer{padding:16px;background:#f0f4f6;border-radius:12px}label{display:block;margin:8px 0}a{color:#176c99}.tag{font-size:12px;color:#697980}
+</style><main><h1>Conversation</h1><p class="hint">Interactive layout preview with sample content, not a connected conversation. Projects start closed. Open one to see its updates and write directly to it.</p>
+<div data-chat-stream><div data-project-catalog hidden><span data-project-id="p1" data-name="Woodstar" data-status="Active"></span><span data-project-id="p2" data-name="Equipo" data-status="Active"></span></div>
+<ol equipo-feed>
+<li data-message="general"><span class="tag">You · 09:15</span><p>What should we prioritise across the team this week?</p></li>
+<li data-message="one" data-project-id="p1" data-turn-id="t1"><span class="tag">You · 09:20</span><p>Explore a simpler way to organise saved articles.</p></li>
+<li data-message="two" data-project-id="p1" data-turn-id="t1"><span class="tag">Equipo · 09:22</span><p>The exploration is ready. A lightweight collection view would keep saved articles easy to find.</p></li>
+<li data-card="c1" data-project-id="p1" data-needs-you="true" data-state="open"><a href="#woodstar">Organise saved articles</a><p>Would you like us to build the collection view?</p><form><label>Anything to adjust? <textarea aria-label="Direction note"></textarea></label><button>Build this</button> <button>Keep exploring</button></form></li>
+<li data-message="three" data-project-id="p2" data-turn-id="t2"><span class="tag">Equipo · 10:05</span><p>The new project navigation is ready for review. Task links and attachments are preserved.</p></li>
+<li data-card="c2" data-project-id="p2" data-needs-you="true" data-state="open"><a href="#equipo">Project navigation</a><p>Review is complete. Ready to merge when you are.</p><form><button>Merge change</button> <button>Request changes</button></form></li>
+</ol>
+<div id="chat-composer"><p data-composer-scope>General conversation</p><form id="composer"><input type="hidden" name="project_id" value=""><textarea aria-label="General conversation" placeholder="What would you like to work on?"></textarea><button>Send</button></form></div></div>
+<p class="hint">Sample action buttons do not submit changes.</p><p id="test-result" hidden></p>
+<script src="project-threads.js"></script><script>document.querySelectorAll('form').forEach(f=>f.addEventListener('submit',e=>e.preventDefault()));</script><script src="browser-test.js"></script></main></html>
diff --git a/release/project-threads/project-threads.js b/release/project-threads/project-threads.js
new file mode 100644
index 00000000..e17ace63
--- /dev/null
+++ b/release/project-threads/project-threads.js
@@ -0,0 +1,127 @@
+// A presentation of one conversation, not independent sessions. Only explicit
+// message scope and card project links are used. Unknown history stays General.
+(function () {
+ "use strict";
+ var catalog = document.querySelector('[data-project-catalog]');
+ if (!catalog) return;
+ var root = document.querySelector('[data-chat-stream]');
+ var feed = root.querySelector('[equipo-feed]');
+ var composer = document.getElementById('chat-composer');
+ var home = composer.parentNode;
+ var input = composer.querySelector('[name=project_id]');
+ var groups = {}, turns = {}, opened = {}, seen = {};
+ var docked = null, focus = null;
+ var known = {};
+ try { seen = JSON.parse(sessionStorage.getItem('equipo:project-reads') || '{}'); } catch (_) {}
+ function readKey(n) { return (n.dataset.message || n.dataset.card) + ':' + (n.dataset.state || ''); }
+ function catalogue(node) {
+ node.querySelectorAll('[data-project-id]').forEach(function (p) {
+ known[p.dataset.projectId] = {name: p.dataset.name, status: p.dataset.status};
+ });
+ }
+ catalogue(catalog);
+ function scope(id) {
+ input.value = id;
+ composer.querySelector('[data-composer-scope]').textContent = id ? 'Message to ' + known[id].name : 'General conversation';
+ composer.querySelector('textarea').setAttribute('aria-label', id ? 'Message to ' + known[id].name : 'General conversation');
+ }
+ function group(id) {
+ if (groups[id] && groups[id].box.isConnected) return groups[id];
+ var li = document.createElement('li'), details = document.createElement('details');
+ li.setAttribute('data-project-thread', id);
+ var summary = document.createElement('summary'), title = document.createElement('strong'), status = document.createElement('span');
+ title.textContent = id ? known[id].name : 'General conversation';
+ summary.append(title, status);
+ var list = document.createElement('ol');
+ list.setAttribute('data-project-messages', id);
+ var button = document.createElement('button');
+ button.type = 'button';
+ button.setAttribute('rst-btn', '');
+ button.textContent = id ? 'Message this project' : 'Message General';
+ button.addEventListener('click', function () {
+ // A draft and its uploads must never silently change destination.
+ if (input.value !== id && (composer.querySelector('textarea').value.trim() || (window.EquipoAttach && window.EquipoAttach.count()))) {
+ composer.querySelector('[data-composer-scope]').textContent += ' · Send or clear this draft before switching projects.';
+ return;
+ }
+ scope(id);
+ docked = id;
+ details.append(composer);
+ composer.querySelector('textarea').focus();
+ });
+ details.append(summary, list, button);
+ details.open = id === '' ? opened[id] !== false : !!opened[id];
+ details.addEventListener('toggle', function () {
+ opened[id] = details.open;
+ if (details.open) markRead(id);
+ if (!details.open && details.contains(composer)) { docked = null; home.append(composer); }
+ update(id);
+ });
+ li.append(details);
+ feed.append(li);
+ groups[id] = {box: li, details: details, list: list, status: status};
+ return groups[id];
+ }
+ function markRead(id) {
+ var g = groups[id];
+ g.list.querySelectorAll('[data-message], [data-card]').forEach(function (n) {
+ seen[readKey(n)] = true;
+ });
+ try { sessionStorage.setItem('equipo:project-reads', JSON.stringify(seen)); } catch (_) {}
+ }
+ function update(id) {
+ var g = groups[id], needs = g.list.querySelectorAll('[data-needs-you="true"]').length;
+ var unread = Array.from(g.list.querySelectorAll('[data-message], [data-card]')).filter(function (n) { return !seen[readKey(n)]; }).length;
+ g.status.textContent = [id ? known[id].status : 'Cross-project requests and unassigned history', needs ? needs + ' needs you' : '', unread ? unread + ' unread' : ''].filter(Boolean).join(' · ');
+ }
+ function arrange() {
+ observer.disconnect();
+ group('');
+ Object.keys(known).forEach(group);
+ feed.querySelectorAll('[data-project-id][data-turn-id], [data-project-id][data-turn]').forEach(function (n) {
+ var turn = n.dataset.turnId || n.dataset.turn;
+ if (turn && n.dataset.projectId && !n.hasAttribute('data-card')) turns[turn] = n.dataset.projectId;
+ });
+ // Keep General's day navigation and history in their original order.
+ Array.from(feed.children).forEach(function (n) {
+ if (!n.hasAttribute('data-project-thread')) groups[''].list.append(n);
+ });
+ // Snapshot the nodes before moving them, preserving their order within
+ // each project, including cards before/after the reply that produced them.
+ Array.from(feed.querySelectorAll('[data-message], [data-card], [equipo-thinking], [data-ended]')).forEach(function (n) {
+ var id = n.dataset.projectId || (!n.hasAttribute('data-card') && turns[n.dataset.turnId || n.dataset.turn]) || '';
+ if (!known[id]) id = '';
+ var g = group(id);
+ if (id === '' && g.list.contains(n)) return;
+ if (n.parentNode !== g.list) g.list.append(n);
+ });
+ Object.keys(groups).forEach(function (id) {
+ if (groups[id].details.open) markRead(id);
+ update(id);
+ });
+ if (docked !== null && groups[docked] && groups[docked].details.open && composer.parentNode !== groups[docked].details) groups[docked].details.append(composer);
+ if (focus) {
+ focus.node.focus({preventScroll: true});
+ if (focus.start !== null) focus.node.setSelectionRange(focus.start, focus.end);
+ focus = null;
+ }
+ observer.observe(feed, {childList: true, subtree: true, attributes: true, attributeFilter: ['data-project-id', 'data-turn', 'data-turn-id', 'data-message']});
+ }
+ var observer = new MutationObserver(arrange);
+ // Refresh replaces the flat server feed. Save the single attachment-aware
+ // composer first; the grouping pass then adopts the new nodes, never copies.
+ window.EquipoProjectThreads = {
+ beforeRefresh: function (doc) {
+ if (feed.contains(composer)) {
+ var active = document.activeElement;
+ if (composer.contains(active)) focus = {node: active, start: typeof active.selectionStart === 'number' ? active.selectionStart : null, end: active.selectionEnd};
+ home.append(composer);
+ }
+ var next = doc.querySelector('[data-project-catalog]');
+ if (next) catalogue(next);
+ },
+ turn: function (id, project) { if (project) turns[id] = project; },
+ arrange: arrange
+ };
+ arrange();
+})();