Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat: live collaborative editing for issue descriptions (MUL-9778) (#11168)

Jiayuan Zhange2967f0c73f9
diff --git a/.env.example b/.env.example
index 77362ea693..e570d4dd89 100644
--- a/.env.example
+++ b/.env.example
@@ -234,6 +234,11 @@ MULTICA_FEATURE_FLAGS_FILE=
# Turn it on for a deployment that is testing it:
# FF_DOCS_V1=true
+# Live co-editing of issue descriptions (MUL-9778) runs on the collab service
+# below and stays off until set. Without it, or without that service, a
+# description saves through the API as it always has:
+# FF_ISSUE_DESCRIPTION_LIVE=true
+
# Workspace subscription Checkout/Portal/entitlement proxying is fail-closed;
# enable it only after multica-cloud billing.subscriptions is configured. For
# multica-cloud deployments only, so the self-host stack does not pass it:
diff --git a/Dockerfile.collab b/Dockerfile.collab
index b523262f6e..1903b76d99 100644
--- a/Dockerfile.collab
+++ b/Dockerfile.collab
@@ -13,6 +13,7 @@ WORKDIR /app
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json .npmrc ./
# Root pnpm patchedDependencies is read even without the mobile workspace.
COPY apps/mobile/patches/ apps/mobile/patches/
+COPY patches/ patches/
COPY apps/collab/package.json apps/collab/
COPY packages/views/package.json packages/views/
COPY packages/core/package.json packages/core/
diff --git a/Dockerfile.web b/Dockerfile.web
index 06a77adf89..32e7e825e9 100644
--- a/Dockerfile.web
+++ b/Dockerfile.web
@@ -14,6 +14,7 @@ COPY apps/web/package.json apps/web/
COPY apps/web/source.config.ts apps/web/source.config.ts
# Root pnpm patchedDependencies is read even without the mobile workspace.
COPY apps/mobile/patches/ apps/mobile/patches/
+COPY patches/ patches/
COPY packages/core/package.json packages/core/
COPY packages/ui/package.json packages/ui/
COPY packages/views/package.json packages/views/
diff --git a/apps/collab/src/api.ts b/apps/collab/src/api.ts
index c6224ad800..b4d631f72f 100644
--- a/apps/collab/src/api.ts
+++ b/apps/collab/src/api.ts
@@ -1,6 +1,9 @@
import type { Actor } from "./ticket";
-/** A stored document as the Go API holds it. */
+/** What a live document holds: a doc, or an issue's description. */
+export type DocumentType = "doc" | "issue";
+
+/** A stored document as the Go API holds it. Issues have no title. */
export interface StoredDocument {
workspace_id: string;
title: string;
@@ -24,10 +27,15 @@ export interface StoreRequest {
task_id?: string;
/** Save only the Yjs state for the current revision; the doc is untouched. */
state_only?: boolean;
+ /** Issues: mentions ("type:id") this session has already stored, which
+ * must not notify again. */
+ seen_mentions?: string[];
+ /** Issues: a save of what people typed rather than one explicit write. */
+ live?: boolean;
}
export type StoreResult =
- | { status: "stored"; revision: number; title: string }
+ | { status: "stored"; revision: number; title: string; mentions: string[] }
| { status: "conflict"; revision: number; content: string }
| { status: "gone" };
@@ -41,7 +49,7 @@ export class ApiError extends Error {
}
/** Client for the Go API's internal collaboration endpoints
- * (server/internal/handler/collab.go). */
+ * (server/internal/handler/doc_collab.go, issue_description_collab.go). */
export class CollabApi {
constructor(
private readonly baseUrl: string,
@@ -60,15 +68,19 @@ export class CollabApi {
});
}
- async loadDoc(id: string): Promise<StoredDocument | null> {
- const res = await this.request(`/internal/collab/docs/${encodeURIComponent(id)}`);
+ private path(type: DocumentType, id: string) {
+ return `/internal/collab/${type === "issue" ? "issues" : "docs"}/${encodeURIComponent(id)}`;
+ }
+
+ async load(type: DocumentType, id: string): Promise<StoredDocument | null> {
+ const res = await this.request(this.path(type, id));
if (res.status === 404) return null;
- if (!res.ok) throw new ApiError(`load doc ${id}: ${res.status} ${await res.text()}`, res.status);
+ if (!res.ok) throw new ApiError(`load ${type} ${id}: ${res.status} ${await res.text()}`, res.status);
return (await res.json()) as StoredDocument;
}
- async storeDoc(id: string, body: StoreRequest): Promise<StoreResult> {
- const res = await this.request(`/internal/collab/docs/${encodeURIComponent(id)}/store`, {
+ async store(type: DocumentType, id: string, body: StoreRequest): Promise<StoreResult> {
+ const res = await this.request(`${this.path(type, id)}/store`, {
method: "POST",
body: JSON.stringify(body),
});
@@ -77,8 +89,8 @@ export class CollabApi {
const data = (await res.json()) as { revision: number; content: string };
return { status: "conflict", revision: data.revision, content: data.content };
}
- if (!res.ok) throw new ApiError(`store doc ${id}: ${res.status} ${await res.text()}`, res.status);
- const data = (await res.json()) as { revision: number; title: string };
- return { status: "stored", revision: data.revision, title: data.title };
+ if (!res.ok) throw new ApiError(`store ${type} ${id}: ${res.status} ${await res.text()}`, res.status);
+ const data = (await res.json()) as { revision: number; title?: string; mentions?: string[] };
+ return { status: "stored", revision: data.revision, title: data.title ?? "", mentions: data.mentions ?? [] };
}
}
diff --git a/apps/collab/src/collab.test.ts b/apps/collab/src/collab.test.ts
index f8e36fcb61..531bd9060a 100644
--- a/apps/collab/src/collab.test.ts
+++ b/apps/collab/src/collab.test.ts
@@ -22,9 +22,14 @@ interface FakeDoc {
revision: number;
ystate: string | null;
ystateRevision: number | null;
- stores: { contributors: string[]; content: string; message?: string }[];
+ stores: { contributors: string[]; content: string; message?: string; live?: boolean; seen?: string[] }[];
}
let fake: FakeDoc;
+const ISSUE_ID = "0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5c";
+const ISSUE_NAME = `issue:${ISSUE_ID}`;
+let fakeIssue: FakeDoc;
+const mentionsIn = (content: string) =>
+ [...content.matchAll(/mention:\/\/(member|agent)\/([0-9a-f-]{36})/g)].map((m) => `${m[1]}:${m[2]}`);
/** When set, stores wait for it before answering. */
let storeGate: { requested: number; release: Promise<void> } | null = null;
let apiServer: HttpServer;
@@ -48,40 +53,49 @@ beforeAll(async () => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
- if (req.method === "GET" && req.url === `/internal/collab/docs/${DOC_ID}`) {
+ const route = /^\/internal\/collab\/(docs|issues)\/([^/]+)(\/store)?$/.exec(req.url ?? "");
+ const issue = route?.[1] === "issues";
+ const target = route && route[2] === (issue ? ISSUE_ID : DOC_ID) ? (issue ? fakeIssue : fake) : null;
+ if (!route || !target) return send(404, {});
+ // Issues have no title; their stores answer with the mentions stored.
+ const stored = () =>
+ issue ? { revision: target.revision, mentions: mentionsIn(target.content) } : { revision: target.revision, title: "T" };
+ if (req.method === "GET" && !route[3]) {
return send(200, {
workspace_id: "ws",
- title: "T",
- content: fake.content,
- revision: fake.revision,
- ystate: fake.ystate,
- ystate_revision: fake.ystateRevision,
+ title: issue ? "" : "T",
+ content: target.content,
+ revision: target.revision,
+ ystate: target.ystate,
+ ystate_revision: target.ystateRevision,
});
}
- if (req.method === "POST" && req.url === `/internal/collab/docs/${DOC_ID}/store`) {
+ if (req.method === "POST" && route[3]) {
const body = JSON.parse(Buffer.concat(chunks).toString());
if (storeGate && !body.state_only) {
storeGate.requested += 1;
await storeGate.release;
}
- if (body.base_revision !== fake.revision) {
- return send(409, { revision: fake.revision, content: fake.content });
+ if (body.base_revision !== target.revision) {
+ return send(409, { revision: target.revision, content: target.content });
}
if (body.state_only) {
- fake.ystate = body.ystate;
- fake.ystateRevision = fake.revision;
- return send(200, { revision: fake.revision, title: "T" });
+ target.ystate = body.ystate;
+ target.ystateRevision = target.revision;
+ return send(200, stored());
}
- fake.revision += 1;
- fake.content = body.content;
- fake.ystate = body.ystate;
- fake.ystateRevision = fake.revision;
- fake.stores.push({
+ target.revision += 1;
+ target.content = body.content;
+ target.ystate = body.ystate;
+ target.ystateRevision = target.revision;
+ target.stores.push({
contributors: body.contributors.map((c: Actor) => c.id),
content: body.content,
message: body.message,
+ live: body.live,
+ seen: body.seen_mentions,
});
- return send(200, { revision: fake.revision, title: "T" });
+ return send(200, stored());
}
send(404, {});
});
@@ -113,20 +127,26 @@ function resetDoc(content: string) {
storeGate = null;
}
-function ticket(actor: Actor) {
+function resetIssue(content: string) {
+ fakeIssue = { content, revision: 7, ystate: null, ystateRevision: null, stores: [] };
+ storeGate = null;
+}
+
+function ticket(actor: Actor, name = NAME) {
return signTicket(
- { document: NAME, workspaceId: "ws", actor, readOnly: false, expiresAt: Math.floor(Date.now() / 1000) + 60 },
+ { document: name, workspaceId: "ws", actor, readOnly: false, expiresAt: Math.floor(Date.now() / 1000) + 60 },
SECRET,
);
}
-async function connect(actor: Actor, opts: { document?: Y.Doc; epoch?: string } = {}) {
+async function connect(actor: Actor, opts: { document?: Y.Doc; epoch?: string; name?: string } = {}) {
const document = opts.document ?? new Y.Doc();
+ const name = opts.name ?? NAME;
const provider = new HocuspocusProvider({
url: collabUrl,
- name: NAME,
+ name,
document,
- token: () => JSON.stringify({ ticket: ticket(actor), epoch: opts.epoch }),
+ token: () => JSON.stringify({ ticket: ticket(actor, name), epoch: opts.epoch }),
});
providers.push(provider);
await waitFor(() => provider.isSynced, 3000);
@@ -148,8 +168,8 @@ function typeInto(doc: Y.Doc, block: number, offset: number, text: string) {
(element.get(0) as Y.XmlText).insert(offset, text);
}
-async function internal(path: "write" | "edit" | "flush", body: unknown) {
- const res = await fetch(`http://127.0.0.1:${collab.server.address.port}/internal/documents/${NAME}/${path}`, {
+async function internal(path: "write" | "edit" | "flush", body: unknown, name = NAME) {
+ const res = await fetch(`http://127.0.0.1:${collab.server.address.port}/internal/documents/${name}/${path}`, {
method: "POST",
headers: { "X-Collab-Secret": SECRET, "Content-Type": "application/json" },
body: JSON.stringify(body),
@@ -511,3 +531,45 @@ describe("collaboration server", () => {
expect(Buffer.from(fake.ystate!, "base64").byteLength).toBeLessThan(10_000);
});
});
+
+describe("issue descriptions", () => {
+ it("saves what editors type to the issue as live, passing on the mentions already stored", async () => {
+ resetIssue(`Hi [@Bob](mention://member/${bob.id})\n\nSecond`);
+ const a = await connect(ada, { name: ISSUE_NAME });
+ const b = await connect(bob, { name: ISSUE_NAME });
+ typeInto(a.document, 1, 6, " line");
+ await waitFor(() => fakeIssue.stores.length === 1, 2000);
+ expect(fakeIssue.stores[0]).toMatchObject({ contributors: [ada.id], live: true, seen: [] });
+ expect(fakeIssue.content).toContain("Second line");
+
+ typeInto(b.document, 1, 11, "!");
+ await waitFor(() => fakeIssue.stores.length === 2, 2000);
+ expect(fakeIssue.stores[1]).toMatchObject({ contributors: [bob.id], live: true, seen: [`member:${bob.id}`] });
+ });
+
+ it("saves an agent's edit to an issue as an explicit write of its own", async () => {
+ resetIssue("Status: draft");
+ const a = await connect(ada, { name: ISSUE_NAME });
+ const result = await internal(
+ "edit",
+ { actor: agent, edits: [{ old_text: "draft", new_text: "approved" }] },
+ ISSUE_NAME,
+ );
+ expect(result.status).toBe(200);
+ expect(result.body.revision).toBe(8);
+ await waitFor(() => markdown(a.document) === "Status: approved");
+ expect(fakeIssue.stores).toEqual([
+ { contributors: [agent.id], content: "Status: approved", message: undefined, live: false, seen: [] },
+ ]);
+ });
+
+ it("reports an issue that no longer exists as gone", async () => {
+ resetIssue("Anything");
+ const result = await internal(
+ "write",
+ { actor: agent, content: "x" },
+ "issue:0193a1b2-c3d4-7e5f-8a9b-000000000000",
+ );
+ expect(result.status).toBe(404);
+ });
+});
diff --git a/apps/collab/src/documents.ts b/apps/collab/src/documents.ts
index 85638126ea..ae35c555a7 100644
--- a/apps/collab/src/documents.ts
+++ b/apps/collab/src/documents.ts
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
import * as Y from "yjs";
import type { Document, Hocuspocus } from "@hocuspocus/server";
import type { DocumentCodec, JSONContent } from "@multica/views/editor/schema/codec";
-import type { CollabApi, StoreRequest } from "./api";
+import type { CollabApi, DocumentType, StoreRequest } from "./api";
import { applyTextEdits, type EditFailure, type TextEdit } from "./edits";
import { keepLiveBlocks, mergeDocuments, type MergeConflict } from "./merge";
import type { Actor } from "./ticket";
@@ -22,9 +22,10 @@ const META_MAP = "meta";
export const COMPACT_STATE_MIN_BYTES = 1 << 20;
export const COMPACT_STATE_RATIO = 4;
-export function parseDocumentName(name: string): { type: "doc"; id: string } | null {
- const match = /^doc:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.exec(name);
- return match ? { type: "doc", id: match[1]!.toLowerCase() } : null;
+/** `doc:<uuid>` is a doc; `issue:<uuid>` is an issue's description. */
+export function parseDocumentName(name: string): { type: DocumentType; id: string } | null {
+ const match = /^(doc|issue):([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.exec(name);
+ return match ? { type: match[1] as DocumentType, id: match[2]!.toLowerCase() } : null;
}
export function documentEpoch(doc: Y.Doc): string | undefined {
@@ -36,7 +37,11 @@ export function documentEpoch(doc: Y.Doc): string | undefined {
const serverOrigin = (actor: Actor) => ({ source: "local" as const, skipStoreHooks: true, context: { actor } });
interface DocState {
+ type: DocumentType;
id: string;
+ /** Issues: mentions stored while this session was loaded. An editor saves
+ * a mention half typed, or deletes and retypes it; it notifies once. */
+ seenMentions: Set<string>;
/** Stored revision the live document was last persisted as. */
revision: number;
/** Canonical Markdown of that revision. */
@@ -110,8 +115,8 @@ export class DocumentStore {
async load(name: string): Promise<Uint8Array> {
const parsed = parseDocumentName(name);
if (!parsed) throw new Error(`unknown document ${name}`);
- const stored = await this.api.loadDoc(parsed.id);
- if (!stored) throw new GoneError(`doc ${parsed.id} not found`);
+ const stored = await this.api.load(parsed.type, parsed.id);
+ if (!stored) throw new GoneError(`${parsed.type} ${parsed.id} not found`);
let ydoc: Y.Doc | null = null;
let from = "markdown";
@@ -144,18 +149,20 @@ export class DocumentStore {
// Save the state now: loading again would otherwise redo the catch-up
// or rebuild with new Yjs items and duplicate text for clients that
// already hold this one.
- const saved = await this.api.storeDoc(parsed.id, {
+ const saved = await this.api.store(parsed.type, parsed.id, {
base_revision: stored.revision,
content: stored.content,
ystate: Buffer.from(Y.encodeStateAsUpdate(ydoc)).toString("base64"),
contributors: [],
state_only: true,
});
- if (saved.status === "gone") throw new GoneError(`doc ${parsed.id} not found`);
- if (saved.status === "conflict") throw new Error(`doc ${parsed.id} changed while loading`);
+ if (saved.status === "gone") throw new GoneError(`${parsed.type} ${parsed.id} not found`);
+ if (saved.status === "conflict") throw new Error(`${parsed.type} ${parsed.id} changed while loading`);
}
this.states.set(name, {
+ type: parsed.type,
id: parsed.id,
+ seenMentions: new Set(),
revision: stored.revision,
persisted: this.codec.ydocToMarkdown(ydoc),
loadedRaw: stored.content,
@@ -163,7 +170,12 @@ export class DocumentStore {
dirty: false,
queue: Promise.resolve(),
});
- this.log.info("loaded", { doc: parsed.id, revision: stored.revision, from, state_bytes: state?.byteLength ?? 0 });
+ this.log.info("loaded", {
+ [parsed.type]: parsed.id,
+ revision: stored.revision,
+ from,
+ state_bytes: state?.byteLength ?? 0,
+ });
return Y.encodeStateAsUpdate(ydoc);
}
@@ -351,10 +363,11 @@ export class DocumentStore {
...(req.action ? { action: req.action } : {}),
...(req.action_ref ? { action_ref: req.action_ref } : {}),
...(req.task_id ? { task_id: req.task_id } : {}),
+ ...(state.type === "issue" ? { seen_mentions: [...state.seenMentions], live: !explicit } : {}),
};
let result;
try {
- result = await this.api.storeDoc(state.id, body);
+ result = await this.api.store(state.type, state.id, body);
} catch (error) {
giveBack();
state.dirty = true;
@@ -378,9 +391,10 @@ export class DocumentStore {
state.revision = result.revision;
state.persisted = content;
state.loadedRaw = null;
+ for (const mention of result.mentions) state.seenMentions.add(mention);
this.lastTitle.set(name, result.title);
this.log.info("stored", {
- doc: state.id,
+ [state.type]: state.id,
revision: result.revision,
contributors: body.contributors.map((c) => `${c.type}:${c.id}`),
});
diff --git a/apps/docs/content/docs/issue-wakeups.fr.mdx b/apps/docs/content/docs/issue-wakeups.fr.mdx
index ffec0be7f3..882e0bce15 100644
--- a/apps/docs/content/docs/issue-wakeups.fr.mdx
+++ b/apps/docs/content/docs/issue-wakeups.fr.mdx
@@ -76,7 +76,6 @@ Quand l'assigné de la tâche est un agent, les commentaires des membres le déc
- Quand une vérification régulière ne trouve rien qui demande une réponse, l'agent peut terminer par une **vérification silencieuse** : pas de commentaire, seulement une note dans l'historique de la tâche et dans l'historique de la règle. Les vérifications silencieuses successives sont regroupées en une seule entrée.
- Les commentaires et les modifications d'un agent ne le réveillent jamais lui-même.
- Si le même agent a déjà une exécution en attente de démarrage sur la tâche, le réveil rejoint cette exécution au lieu d'en lancer une autre.
-- Tant qu'un réveil attend, l'en-tête de la tâche indique ce qu'elle attend, par exemple « Assistant ops : Attend une réponse ». Un clic mène à la section Réveils.
## Étapes de workflow sur un travail poursuivi [#workflow-steps]
diff --git a/apps/docs/content/docs/issue-wakeups.ja.mdx b/apps/docs/content/docs/issue-wakeups.ja.mdx
index 87299b9c83..c969b80a7e 100644
--- a/apps/docs/content/docs/issue-wakeups.ja.mdx
+++ b/apps/docs/content/docs/issue-wakeups.ja.mdx
@@ -76,7 +76,6 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";
- 定期チェックで返信が必要なことが何もなければ、エージェントは**サイレントチェック**で終えられます。コメントは投稿せず、タスクのタイムラインとルールの起動履歴にメモだけを残します。続いたサイレントチェックはタイムラインで 1 件にまとまります。
- エージェント自身のコメントやタスクへの変更で、そのエージェントが起こされることはありません。
- 同じエージェントの実行がこのタスクで開始待ちなら、ウェイクアップはその実行に合流し、別の実行は始めません。
-- ウェイクアップが待っている間、タスクのヘッダーには「運用アシスタント:返信待ち」のように、タスクが何を待っているかが表示されます。クリックするとウェイクアップ欄に移動します。
## 継続作業時のワークフローステップ [#workflow-steps]
diff --git a/apps/docs/content/docs/issue-wakeups.ko.mdx b/apps/docs/content/docs/issue-wakeups.ko.mdx
index 22eea4fa34..5ec1574883 100644
--- a/apps/docs/content/docs/issue-wakeups.ko.mdx
+++ b/apps/docs/content/docs/issue-wakeups.ko.mdx
@@ -76,7 +76,6 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";
- 정기 확인에서 답할 만한 일이 없으면 에이전트는 **조용한 확인**으로 끝낼 수 있습니다. 댓글은 남기지 않고, 태스크 타임라인과 규칙의 실행 기록에 메모만 남깁니다. 연달아 이어진 조용한 확인은 타임라인에서 한 줄로 합쳐집니다.
- 에이전트가 직접 남긴 댓글이나 태스크 변경으로는 그 에이전트가 깨어나지 않습니다.
- 같은 에이전트의 실행이 이 태스크에서 시작을 기다리고 있으면, 깨우기는 그 실행에 합쳐지고 실행을 하나 더 만들지 않습니다.
-- 깨우기가 기다리는 동안 태스크 헤더에 "운영 도우미: 답글 대기"처럼 태스크가 무엇을 기다리는지 표시됩니다. 클릭하면 깨우기 영역으로 이동합니다.
## 이어서 진행하는 작업의 워크플로 단계 [#workflow-steps]
diff --git a/apps/docs/content/docs/issue-wakeups.mdx b/apps/docs/content/docs/issue-wakeups.mdx
index 9f8bb1b0c8..a40ce94f02 100644
--- a/apps/docs/content/docs/issue-wakeups.mdx
+++ b/apps/docs/content/docs/issue-wakeups.mdx
@@ -76,7 +76,6 @@ When the issue's assignee is an agent, members' comments already trigger it. A "
- When a regular check finds nothing that needs a reply, the agent can end with a **silent check**: no comment, only a note in the issue timeline and in the rule's trigger history. Consecutive silent checks collapse into one timeline entry.
- An agent's own comments and its own changes to the issue never wake it.
- If the same agent already has a run waiting to start on the issue, the wakeup joins that run instead of starting another one.
-- While a wakeup is waiting, the issue header shows what the issue is waiting for, such as "Ops helper: Waiting for a reply". Click it to jump to the Wakeups section.
## Workflow steps on continued work [#workflow-steps]
diff --git a/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx b/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx
index e7028aaf74..092f94f35b 100644
--- a/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx
+++ b/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx
@@ -76,7 +76,6 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";
- 定期檢查沒發現需要回復的事,AI 代理可以**靜默檢查**後結束:不發評論,只在任務時間線和這條喚醒的觸發記錄裡留一條說明。連續幾次靜默檢查在時間線裡合併成一條。
- AI 代理自己發的評論、自己對任務的修改,不會喚醒它自己。
- 同一個 AI 代理在這條任務上已經有一次執行在等待開始,新的喚醒會併入那次執行,不再另起一次。
-- 有喚醒在等時,任務標題旁會顯示任務在等什麼,例如"運營助手 在等回覆",點一下跳到喚醒區域。
## 續跑時的工作流步驟 [#workflow-steps]
diff --git a/apps/docs/content/docs/issue-wakeups.zh.mdx b/apps/docs/content/docs/issue-wakeups.zh.mdx
index 15036245d7..59ccd7af23 100644
--- a/apps/docs/content/docs/issue-wakeups.zh.mdx
+++ b/apps/docs/content/docs/issue-wakeups.zh.mdx
@@ -76,7 +76,6 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";
- 定期检查没发现需要回复的事,智能体可以**静默检查**后结束:不发评论,只在任务时间线和这条唤醒的触发记录里留一条说明。连续几次静默检查在时间线里合并成一条。
- 智能体自己发的评论、自己对任务的修改,不会唤醒它自己。
- 同一个智能体在这条任务上已经有一次运行在等待开始,新的唤醒会并入那次运行,不再另起一次。
-- 有唤醒在等时,任务标题旁会显示任务在等什么,例如"运营助手 在等回复",点一下跳到唤醒区域。
## 续跑时的工作流步骤 [#workflow-steps]
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index a6b7fdcae8..640d1584aa 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -190,6 +190,7 @@ backend:
# value turns the flag off. Values: true, false, a percent like "25%", or
# a variant name. The flags documented in .env.example:
# docs_v1: true # Workspace Docs, off until set
+ # issue_description_live: true # live issue descriptions, needs collab
# local_search_index: false # kill switch, on by default
# dashboard_history_365d: false # kill switch, on by default
featureFlags: {}
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 9400dadab5..2d11afe7db 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -257,9 +257,11 @@ services:
MULTICA_TELEGRAM_TOOL_PROGRESS: ${MULTICA_TELEGRAM_TOOL_PROGRESS:-}
# Feature flags, documented in .env.example. Each is passed only when
# set: an empty FF_ value would pin the flag off instead of leaving the
- # default. Workspace Docs is off until FF_DOCS_V1=true; the other two are
+ # default. Workspace Docs is off until FF_DOCS_V1=true and live issue
+ # descriptions until FF_ISSUE_DESCRIPTION_LIVE=true; the other two are
# kill switches for features that are on by default.
FF_DOCS_V1:
+ FF_ISSUE_DESCRIPTION_LIVE:
FF_LOCAL_SEARCH_INDEX:
FF_DASHBOARD_HISTORY_365D:
# Live co-editing for Workspace Docs, served by the optional collab
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index 3a79944480..326677a1e1 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -474,6 +474,29 @@ export class TestApiClient {
return res.json();
}
+ async getIssue(id: string) {
+ const res = await this.authedFetch(`/api/issues/${id}`);
+ if (!res.ok) throw new Error(`get issue: ${res.status}`);
+ return await res.json() as {id: string; status: string; description: string | null; description_revision?: number};
+ }
+
+ /** The local edit `multica issue edit-description` sends. */
+ async editIssueDescription(id: string, oldText: string, newText: string) {
+ const res = await this.authedFetch(`/api/issues/${id}/description/edits`, {
+ method: "POST",
+ body: JSON.stringify({ edits: [{ old_text: oldText, new_text: newText }] }),
+ });
+ if (!res.ok) throw new Error(`edit issue description: ${res.status} ${await res.text()}`);
+ return await res.json() as {description: string | null};
+ }
+
+ async listIssueActivity(id: string) {
+ const res = await this.authedFetch(`/api/issues/${id}/timeline`);
+ if (!res.ok) throw new Error(`issue timeline: ${res.status}`);
+ const entries = await res.json() as {type: string; action?: string; actor_id: string; details?: Record<string, string>}[];
+ return entries.filter((entry) => entry.type === "activity");
+ }
+
/** Clean up all issues created during this test. */
async cleanup() {
for (const id of this.createdDocIds) await this.authedFetch(`/api/docs/${id}`, {method: "DELETE"});
diff --git a/e2e/issue-description-live.spec.ts b/e2e/issue-description-live.spec.ts
new file mode 100644
index 0000000000..ab05021596
--- /dev/null
+++ b/e2e/issue-description-live.spec.ts
@@ -0,0 +1,178 @@
+import { test, expect, type Browser, type Page } from "@playwright/test";
+// Live issue descriptions need collab and the issue_description_live flag:
+// run `make up` with FF_ISSUE_DESCRIPTION_LIVE=true. Without them the issue
+// page keeps its solo editor and this spec skips.
+import { TestApiClient } from "./fixtures";
+
+let alice: TestApiClient;
+let bob: TestApiClient;
+let slug: string;
+test.beforeEach(async () => {
+ const suffix = `${Date.now()}-${test.info().workerIndex}`;
+ bob = new TestApiClient();
+ await bob.login(`issue-live-bob-${suffix}@multica.ai`, "Bob Chen");
+ await bob.markUserOnboarded();
+ alice = new TestApiClient();
+ await alice.login(`issue-live-alice-${suffix}@multica.ai`, "Alice Park");
+ slug = (await alice.ensureWorkspace("Launch team", `issue-live-${suffix}`)).slug;
+ await alice.markUserOnboarded();
+ await alice.addMemberByEmail(bob.getEmail());
+});
+test.afterEach(async () => {
+ await alice.cleanup();
+ await alice.deleteWorkspace();
+});
+
+/** Opens the issue as `token` and waits for the live editor to take over from the solo one. */
+async function openLive(browser: Browser, token: string, issueId: string) {
+ const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
+ const page = await context.newPage();
+ page.on("pageerror", (error) => {
+ throw error;
+ });
+ await page.addInitScript((t) => {
+ localStorage.setItem("multica_token", t);
+ localStorage.setItem("multica:chat:isOpen", "false");
+ }, token);
+ const ticket = page.waitForResponse((response) => response.url().endsWith(`/api/issues/${issueId}/collab-ticket`));
+ await page.goto(`/${slug}/issues/${issueId}`);
+ const live = ((await (await ticket).json()) as { enabled?: boolean }).enabled === true;
+ const editor = description(page);
+ await expect(editor).toBeVisible();
+ if (live) {
+ // The solo editor unmounts once the live one is shown.
+ await editor.evaluate((element) => element.setAttribute("data-e2e-solo", ""));
+ await expect(page.locator("[data-e2e-solo]")).toHaveCount(0, { timeout: 15_000 });
+ }
+ return { page, live };
+}
+
+function description(page: Page) {
+ return page.locator('[data-comment-content^="description:"] .ProseMirror[contenteditable="true"]:visible');
+}
+
+/** The description's text without collaborators' carets, one line per block. */
+async function descriptionText(page: Page) {
+ return description(page).evaluate((element) => {
+ const copy = element.cloneNode(true) as HTMLElement;
+ copy.querySelectorAll(".collaboration-carets__caret").forEach((caret) => caret.remove());
+ return Array.from(copy.children, (block) => block.textContent ?? "").join("\n");
+ });
+}
+
+async function typeAt(page: Page, anchor: string, key: "Home" | "End", text: string) {
+ await description(page).getByText(anchor).click();
+ await page.keyboard.press(key);
+ await page.keyboard.type(text, { delay: 20 });
+}
+
+test("two people and an API edit share one live description", async ({ browser }, info) => {
+ const issue = await alice.createIssue("Launch plan", {
+ description: "Goals for the launch.\n\nOpen questions remain.",
+ });
+ const a = await openLive(browser, alice.getToken()!, issue.id);
+ test.skip(!a.live, "Live issue descriptions are off; start collab with FF_ISSUE_DESCRIPTION_LIVE=true.");
+ const b = await openLive(browser, bob.getToken()!, issue.id);
+
+ // Both type at once, in different paragraphs; a status change and a
+ // local edit through the API land while they are still typing.
+ await Promise.all([
+ typeAt(a.page, "Goals for the launch.", "End", " Ship on Friday."),
+ typeAt(b.page, "Open questions remain.", "Home", "Bob: "),
+ (async () => {
+ await alice.updateIssue(issue.id, { status: "in_progress" });
+ await alice.editIssueDescription(issue.id, "Open questions", "Two open questions");
+ })(),
+ ]);
+
+ const expected = "Goals for the launch. Ship on Friday.\n\nBob: Two open questions remain.";
+ for (const { page } of [a, b]) {
+ await expect.poll(() => descriptionText(page)).toBe(expected.replace("\n\n", "\n"));
+ }
+ await expect(a.page.locator(".collaboration-carets__label", { hasText: "Bob Chen" })).toBeVisible();
+ await expect
+ .poll(async () => (await alice.getIssue(issue.id)).description, { timeout: 20_000 })
+ .toBe(expected);
+ expect((await alice.getIssue(issue.id)).status).toBe("in_progress");
+ await a.page.screenshot({ path: info.outputPath("issue-description-live.png"), animations: "disabled" });
+
+ // After a refresh everyone reads the same Markdown.
+ await b.page.reload();
+ await expect.poll(() => descriptionText(b.page)).toBe(expected.replace("\n\n", "\n"));
+
+ // One entry per live editor for the session, plus the API edit.
+ const updates = (await alice.listIssueActivity(issue.id)).filter(
+ (entry) => entry.action === "description_updated",
+ );
+ expect(updates.filter((entry) => entry.details?.live === "true")).toHaveLength(2);
+ expect(updates).toHaveLength(3);
+ await a.page.context().close();
+ await b.page.context().close();
+});
+
+test("typing before the live session is ready keeps the solo editor until it loses focus", async ({ browser }) => {
+ const issue = await alice.createIssue("Launch plan", { description: "Draft notes." });
+ const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
+ const page = await context.newPage();
+ await page.addInitScript((t) => {
+ localStorage.setItem("multica_token", t);
+ localStorage.setItem("multica:chat:isOpen", "false");
+ }, alice.getToken()!);
+ let release = () => {};
+ const held = new Promise<void>((resolve) => (release = resolve));
+ await page.route(`**/api/issues/${issue.id}/collab-ticket`, async (route) => {
+ await held;
+ await route.continue();
+ });
+ const ticket = page.waitForResponse((response) => response.url().endsWith(`/api/issues/${issue.id}/collab-ticket`));
+ await page.goto(`/${slug}/issues/${issue.id}`);
+ await expect(page.getByText("created this issue")).toBeVisible();
+
+ await typeAt(page, "Draft notes.", "End", " First half.");
+ await description(page).evaluate((element) => element.setAttribute("data-e2e-solo", ""));
+ release();
+ const live = ((await (await ticket).json()) as { enabled?: boolean }).enabled === true;
+ test.skip(!live, "Live issue descriptions are off; start collab with FF_ISSUE_DESCRIPTION_LIVE=true.");
+ // The live editor mounts hidden once it is ready.
+ await expect(page.locator('[data-comment-content^="description:"] .ProseMirror')).toHaveCount(2, { timeout: 15_000 });
+
+ await page.keyboard.type(" Second half.", { delay: 20 });
+ await expect(page.locator("[data-e2e-solo]")).toBeFocused();
+ await expect(page.locator("[data-e2e-solo]")).toHaveText("Draft notes. First half. Second half.");
+
+ await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
+ await expect(page.locator("[data-e2e-solo]")).toHaveCount(0);
+ await expect.poll(() => descriptionText(page), { timeout: 20_000 }).toBe("Draft notes. First half. Second half.");
+ await expect
+ .poll(async () => (await alice.getIssue(issue.id)).description, { timeout: 20_000 })
+ .toBe("Draft notes. First half. Second half.");
+ await context.close();
+});
+
+test("the header shows who else is on the issue and where they are editing", async ({ browser }) => {
+ const issue = await alice.createIssue("Launch plan", {
+ description: "## Goals\n\nShip on Friday.\n\n## Risks\n\nThe import API may slip.",
+ });
+ const a = await openLive(browser, alice.getToken()!, issue.id);
+ test.skip(!a.live, "Live issue descriptions are off; start collab with FF_ISSUE_DESCRIPTION_LIVE=true.");
+ const chip = a.page.getByRole("button", { name: "1 viewing" });
+ await expect(chip).toHaveCount(0);
+
+ const b = await openLive(browser, bob.getToken()!, issue.id);
+ await expect(chip).toBeVisible();
+ await chip.click();
+ await expect(a.page.getByText("Viewing · 1")).toBeVisible();
+ await expect(a.page.locator('[data-presence-row="Bob Chen"]')).toBeVisible();
+ await a.page.keyboard.press("Escape");
+
+ await typeAt(b.page, "The import API may slip.", "End", " Bob owns it.");
+ await chip.click();
+ await expect(a.page.getByText("Editing · 1")).toBeVisible();
+ await expect(a.page.getByText('In "Risks"')).toBeVisible();
+ await a.page.locator('[data-presence-row="Bob Chen"]').click();
+ await expect(a.page.locator('.collaboration-carets__caret[data-collaborator^="member:"]')).toBeInViewport();
+
+ await b.page.context().close();
+ await expect(chip).toHaveCount(0, { timeout: 15_000 });
+ await a.page.context().close();
+});
diff --git a/package.json b/package.json
index 670bc9cd03..64a1542252 100644
--- a/package.json
+++ b/package.json
@@ -61,7 +61,8 @@
"builder-util-runtime": "9.7.0"
},
"patchedDependencies": {
- "[email protected]": "apps/mobile/patches/[email protected]"
+ "[email protected]": "apps/mobile/patches/[email protected]",
+ "@tiptap/[email protected]": "patches/@[email protected]"
}
},
"devDependencies": {
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index eef85fcfa1..ee4a0c44e7 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -1112,6 +1112,18 @@ export class ApiClient {
{ endpoint: "POST /api/docs/{id}/collab-ticket" },
);
}
+ /** Joins the live session of an issue's description; same shape as a doc's. */
+ async createIssueCollabTicket(id: string, options?: { state?: boolean }): Promise<DocCollabTicket> {
+ return parseWithFallback<DocCollabTicket>(
+ await this.fetch<unknown>(`/api/issues/${id}/collab-ticket`, {
+ method: "POST",
+ ...(options?.state ? { body: JSON.stringify({ state: true }) } : {}),
+ }),
+ DocCollabTicketSchema,
+ { enabled: false },
+ { endpoint: "POST /api/issues/{id}/collab-ticket" },
+ );
+ }
async getDocVersion(id: string, number: number): Promise<DocVersion | null> {
return parseWithFallback<DocVersion | null>(
await this.fetch<unknown>(`/api/docs/${id}/versions/${number}`),
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 6a42f4a4f7..eb77e6b83f 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -1757,6 +1757,7 @@ export const IssueSchema = z.object({
created_at: z.string(),
updated_at: z.string(),
revision: z.number().int().positive().optional(),
+ description_revision: z.number().int().nonnegative().optional(),
// Optional for compatibility with older self-hosted backends; a current
// backend emits null until its historical backfill reaches the issue.
last_activity_at: z.string().nullable().optional(),
diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.ts
index 32a5f94569..8b4e19a308 100644
--- a/packages/core/types/issue.ts
+++ b/packages/core/types/issue.ts
@@ -240,6 +240,8 @@ export interface Issue {
updated_at: string;
/** Monotonic server revision; absent when connected to an older backend. */
revision?: number;
+ /** Moves only when the description changes; absent on older backends. */
+ description_revision?: number;
/**
* Null until the server's historical activity backfill reaches this row.
* This RFC3339 timestamp may include sub-second precision while legacy
diff --git a/packages/ui/components/ui/resizable.tsx b/packages/ui/components/ui/resizable.tsx
index f57365c1f2..809dee3537 100644
--- a/packages/ui/components/ui/resizable.tsx
+++ b/packages/ui/components/ui/resizable.tsx
@@ -1,5 +1,6 @@
"use client"
+import * as React from "react"
import * as ResizablePrimitive from "react-resizable-panels"
import { cn } from "@multica/ui/lib/utils"
@@ -15,18 +16,11 @@ function ResizablePanelGroup({
// while dragging, and narrows it to a one-way arrow the moment a panel
// hits a bound — so the cursor flips between two icons mid-drag. It is
// truthful, but it reads as a glitch. The handle carries `cursor-col-resize`
- // instead, which stays put.
+ // instead, which stays put; during a drag `data-resizing` on <html>
+ // (see ResizableHandle) keeps it wherever the pointer travels.
disableCursor
className={cn(
"flex h-full w-full aria-[orientation=vertical]:flex-col",
- // A drag captures the pointer, which then travels across the panels —
- // away from the handle that carries the cursor. `:has` puts the same
- // cursor on the whole group for as long as a separator is active, which
- // is what the library's global rule was doing before `disableCursor`
- // turned it off. Without this the cursor reverts to a text caret the
- // moment the pointer leaves the 8px handle.
- "[&:has([data-separator=active])_*]:cursor-col-resize [&:has([data-separator=active])]:cursor-col-resize",
- "aria-[orientation=vertical]:[&:has([data-separator=active])_*]:cursor-row-resize aria-[orientation=vertical]:[&:has([data-separator=active])]:cursor-row-resize",
className
)}
{...props}
@@ -38,16 +32,63 @@ function ResizablePanel({ ...props }: ResizablePrimitive.PanelProps) {
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />
}
+/**
+ * Marks <html> with `data-resizing="col" | "row"` while this separator is
+ * dragged. A drag captures the pointer, which then travels across the panels,
+ * away from the handle that carries the cursor; base.css puts the same cursor
+ * on everything for as long as the mark is there. A `:has()` on the group
+ * would do the same without script, but it makes every DOM change inside the
+ * panels restyle their whole subtree, which live editing does many times a
+ * second.
+ */
+function useResizingMark(element: HTMLDivElement | null) {
+ React.useEffect(() => {
+ if (!element) return
+ const root = element.ownerDocument.documentElement
+ let marked = false
+ const sync = () => {
+ const active = element.getAttribute("data-separator") === "active"
+ if (active === marked) return
+ marked = active
+ if (active) {
+ root.dataset.resizing =
+ element.getAttribute("aria-orientation") === "horizontal" ? "row" : "col"
+ } else {
+ delete root.dataset.resizing
+ }
+ }
+ const observer = new MutationObserver(sync)
+ observer.observe(element, { attributes: true, attributeFilter: ["data-separator"] })
+ sync()
+ return () => {
+ observer.disconnect()
+ if (marked) delete root.dataset.resizing
+ }
+ }, [element])
+}
+
function ResizableHandle({
withHandle,
className,
+ elementRef,
...props
}: ResizablePrimitive.SeparatorProps & {
withHandle?: boolean
}) {
+ const [element, setElement] = React.useState<HTMLDivElement | null>(null)
+ useResizingMark(element)
+ const ref = React.useCallback(
+ (node: HTMLDivElement | null) => {
+ setElement(node)
+ if (typeof elementRef === "function") elementRef(node)
+ else if (elementRef) elementRef.current = node
+ },
+ [elementRef]
+ )
return (
<ResizablePrimitive.Separator
data-slot="resizable-handle"
+ elementRef={ref}
className={cn(
// The only cursor source: the group opts out of the library's own
// (see ResizablePanelGroup). One icon for hover and for the whole drag.
diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.css
index 5754df79b9..69670eeb77 100644
--- a/packages/ui/styles/base.css
+++ b/packages/ui/styles/base.css
@@ -376,7 +376,18 @@ html[data-sidebar-resizing="true"] {
transition-timing-function: cubic-bezier(0.22, 1, 0.36, 1);
}
-[data-group]:has(> [data-separator="active"]) > [data-right-sidebar-panel] {
+/* While a panel separator is dragged (ResizableHandle marks <html>), the
+ * resize cursor follows the captured pointer across the panels, and the
+ * right sidebar's flex-grow tracks the pointer without easing. */
+html[data-resizing="col"] * {
+ cursor: col-resize;
+}
+
+html[data-resizing="row"] * {
+ cursor: row-resize;
+}
+
+html[data-resizing] [data-right-sidebar-panel] {
transition: none;
}
diff --git a/packages/views/docs/components/doc-live-session.test.ts b/packages/views/docs/components/doc-live-session.test.ts
index 68b6a295f4..717e350052 100644
--- a/packages/views/docs/components/doc-live-session.test.ts
+++ b/packages/views/docs/components/doc-live-session.test.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as Y from "yjs";
const { apiMock, providers, sockets } = vi.hoisted(() => ({
- apiMock: { createDocCollabTicket: vi.fn() },
+ apiMock: { createDocCollabTicket: vi.fn(), createIssueCollabTicket: vi.fn() },
providers: [] as Array<{
config: {
name: string;
@@ -11,7 +11,7 @@ const { apiMock, providers, sockets } = vi.hoisted(() => ({
onClose: (e: { event: { reason: string } }) => void;
};
destroyed: boolean;
- awareness: { local: unknown };
+ awareness: { local: unknown; states: Map<number, unknown>; emit: () => void };
}>,
sockets: [] as Array<{ destroyed: boolean }>,
}));
@@ -32,9 +32,20 @@ vi.mock("@hocuspocus/provider", () => {
destroyed = false;
awareness = {
local: {} as unknown,
- on() {},
- off() {},
- getStates: () => new Map(),
+ states: new Map<number, unknown>(),
+ listeners: new Set<() => void>(),
+ on(_event: string, listener: () => void) {
+ this.listeners.add(listener);
+ },
+ off(_event: string, listener: () => void) {
+ this.listeners.delete(listener);
+ },
+ emit() {
+ for (const listener of this.listeners) listener();
+ },
+ getStates() {
+ return this.states;
+ },
getLocalState() {
return this.local;
},
@@ -61,6 +72,7 @@ import {
acquireDocSession,
findDocSession,
liveEditingOff,
+ liveOffKey,
peekDocLive,
prefetchDocLive,
releaseDocSession,
@@ -88,6 +100,7 @@ const ticket = (docId: string, extra: Record<string, unknown> = {}) => ({
beforeEach(() => {
apiMock.createDocCollabTicket.mockReset();
+ apiMock.createIssueCollabTicket.mockReset();
providers.length = 0;
sockets.length = 0;
});
@@ -129,6 +142,34 @@ describe("prefetchDocLive", () => {
expect(sockets).toHaveLength(2);
});
+ it("asks for an issue description's ticket apart from a doc with the same id", async () => {
+ const { url, docId: id } = ids();
+ apiMock.createDocCollabTicket.mockResolvedValue(ticket(id));
+ apiMock.createIssueCollabTicket.mockResolvedValue({ ...ticket(id), document: `issue:${id}` });
+ await prefetchDocLive(url, id, "u1", "issue");
+ expect(apiMock.createIssueCollabTicket).toHaveBeenCalledWith(id, { state: true });
+ expect(apiMock.createDocCollabTicket).not.toHaveBeenCalled();
+ expect(peekDocLive(url, id, "u1")).toBeUndefined();
+ expect(peekDocLive(url, id, "u1", "issue")).toMatchObject({ document: `issue:${id}` });
+
+ const session = acquireDocSession(url, id, "u1", `issue:${id}`, "issue");
+ expect(findDocSession(url, id, "u1")).toBeUndefined();
+ expect(findDocSession(url, id, "u1", "issue")).toBe(session);
+ // The seeded ticket is used once; the next join asks the issue endpoint.
+ await providers.at(-1)!.config.token();
+ await providers.at(-1)!.config.token();
+ expect(apiMock.createIssueCollabTicket).toHaveBeenLastCalledWith(id, undefined);
+ releaseDocSession(session, { discard: true });
+ });
+
+ it("remembers live issue descriptions being off without turning docs solo", async () => {
+ const { url, docId: id } = ids();
+ apiMock.createIssueCollabTicket.mockResolvedValue({ enabled: false });
+ await prefetchDocLive(url, id, "u1", "issue");
+ expect(liveEditingOff.has(liveOffKey(url, "issue"))).toBe(true);
+ expect(liveEditingOff.has(url)).toBe(false);
+ });
+
it("keeps answers per user: a ticket is personal", async () => {
const { url, docId } = ids();
apiMock.createDocCollabTicket.mockResolvedValue(ticket(docId));
@@ -223,6 +264,34 @@ describe("doc sessions", () => {
releaseDocSession(session, { discard: true });
});
+ it("tells people editing from people who only have the doc open", () => {
+ const { url, docId } = ids();
+ const session = acquireDocSession(url, docId, "u1", `doc:${docId}`);
+ const awareness = providers.at(-1)!.awareness;
+ const caret = { anchor: {}, head: {} };
+ const moves = vi.fn();
+ const stop = session.watchAwareness(moves);
+ awareness.states = new Map<number, unknown>([
+ [101, { user: { id: "a", name: "Ann", kind: "member" } }],
+ // Bo in two tabs, typing in the second.
+ [102, { user: { id: "b", name: "Bo", kind: "member" } }],
+ [103, { user: { id: "b", name: "Bo", kind: "member" }, cursor: caret }],
+ ]);
+ awareness.emit();
+ const people = () => session.getState().collaborators.map((c) => [c.name, c.editing, c.key]);
+ expect(people()).toEqual([["Ann", false, 101], ["Bo", true, 103]]);
+ expect(moves).toHaveBeenCalledTimes(1);
+
+ awareness.states.set(103, { user: { id: "b", name: "Bo", kind: "member" }, cursor: null });
+ awareness.emit();
+ expect(people()).toEqual([["Ann", false, 101], ["Bo", false, 102]]);
+
+ stop();
+ awareness.emit();
+ expect(moves).toHaveBeenCalledTimes(2);
+ releaseDocSession(session, { discard: true });
+ });
+
it("shares one socket between docs on the same server", () => {
const { url, docId } = ids();
const a = acquireDocSession(url, docId, "u1", `doc:${docId}`);
diff --git a/packages/views/docs/components/doc-live-session.ts b/packages/views/docs/components/doc-live-session.ts
index c07b92e7c8..865ceb6722 100644
--- a/packages/views/docs/components/doc-live-session.ts
+++ b/packages/views/docs/components/doc-live-session.ts
@@ -22,7 +22,9 @@ import type { DocCollabTicket } from "@multica/core/types";
*/
/** Servers that answered that live editing is off. That is server
- * configuration, so later docs open for solo editing without asking again. */
+ * configuration, so later docs open for solo editing without asking again.
+ * Docs are keyed by the server's URL, other kinds by `liveOffKey`: each kind
+ * is switched on separately. */
export const liveEditingOff = new Set<string>();
/** Servers that answered that live editing is on; their socket can open
* before the next answer arrives. */
@@ -43,6 +45,8 @@ export interface DocCollaborator {
name: string;
color: string;
kind: "member" | "agent";
+ /** Has a caret in the document, as opposed to only having it open. */
+ editing: boolean;
}
// ---- Ticket and saved state --------------------------------------------------
@@ -61,30 +65,46 @@ interface LiveInfo {
value?: DocCollabTicket;
}
+/** What a session edits: a doc, or the description of an issue. */
+export type LiveKind = "doc" | "issue";
+
+export const liveOffKey = (collabUrl: string, kind: LiveKind) =>
+ kind === "doc" ? collabUrl : `${kind}\n${collabUrl}`;
+
+function requestTicket(kind: LiveKind, id: string, options?: { state?: boolean }): Promise<DocCollabTicket> {
+ return kind === "issue" ? api.createIssueCollabTicket(id, options) : api.createDocCollabTicket(id, options);
+}
+
/** Tickets are personal, so answers are kept per user like sessions are. */
const liveInfos = new Map<string, LiveInfo>();
-const infoKey = (collabUrl: string, docId: string, userId: string) => `${collabUrl}\n${docId}\n${userId}`;
+const infoKey = (collabUrl: string, docId: string, userId: string, kind: LiveKind) =>
+ `${collabUrl}\n${kind === "doc" ? docId : `${kind}:${docId}`}\n${userId}`;
/**
* Asks for the doc's ticket and saved state, unless a recent answer is on
* hand or on its way. Also opens the shared socket of a server known to edit
* live, so it is up by the time the doc joins.
*/
-export function prefetchDocLive(collabUrl: string, docId: string, userId: string): Promise<DocCollabTicket> {
- const key = infoKey(collabUrl, docId, userId);
+export function prefetchDocLive(
+ collabUrl: string,
+ docId: string,
+ userId: string,
+ kind: LiveKind = "doc",
+): Promise<DocCollabTicket> {
+ const key = infoKey(collabUrl, docId, userId, kind);
const cached = liveInfos.get(key);
if (cached && Date.now() - cached.at < LIVE_INFO_MAX_AGE_MS) return cached.promise;
const info: LiveInfo = { at: Date.now(), promise: Promise.resolve({ enabled: false }) };
- info.promise = api.createDocCollabTicket(docId, { state: true }).then(
+ info.promise = requestTicket(kind, docId, { state: true }).then(
(ticket) => {
info.value = ticket;
if (ticket.enabled) {
- liveEditingOff.delete(collabUrl);
+ liveEditingOff.delete(liveOffKey(collabUrl, kind));
if (!liveEditingOn.has(collabUrl)) warmSocket(collabUrl);
liveEditingOn.add(collabUrl);
} else {
- liveEditingOff.add(collabUrl);
- liveEditingOn.delete(collabUrl);
+ liveEditingOff.add(liveOffKey(collabUrl, kind));
+ if (kind === "doc") liveEditingOn.delete(collabUrl);
}
return ticket;
},
@@ -103,16 +123,21 @@ export function prefetchDocLive(collabUrl: string, docId: string, userId: string
}
/** The answer of a recent `prefetchDocLive`, if it has arrived. */
-export function peekDocLive(collabUrl: string, docId: string, userId: string): DocCollabTicket | undefined {
- const info = liveInfos.get(infoKey(collabUrl, docId, userId));
+export function peekDocLive(
+ collabUrl: string,
+ docId: string,
+ userId: string,
+ kind: LiveKind = "doc",
+): DocCollabTicket | undefined {
+ const info = liveInfos.get(infoKey(collabUrl, docId, userId, kind));
return info && Date.now() - info.at < LIVE_INFO_MAX_AGE_MS ? info.value : undefined;
}
/** Takes the answer for a session about to start: its state describes the
* doc only until the session moves on, so it is used once. */
-function takeDocLive(collabUrl: string, docId: string, userId: string): LiveTicket | undefined {
- const value = peekDocLive(collabUrl, docId, userId);
- liveInfos.delete(infoKey(collabUrl, docId, userId));
+function takeDocLive(collabUrl: string, docId: string, userId: string, kind: LiveKind): LiveTicket | undefined {
+ const value = peekDocLive(collabUrl, docId, userId, kind);
+ liveInfos.delete(infoKey(collabUrl, docId, userId, kind));
return value?.enabled ? value : undefined;
}
@@ -206,6 +231,7 @@ export class DocSession {
private readonly docId: string,
readonly document: string,
seed: LiveTicket | undefined,
+ private readonly kind: LiveKind = "doc",
) {
this.ticket = seed ?? null;
let seeded = false;
@@ -232,7 +258,7 @@ export class DocSession {
// Asked on every (re)join. The epoch names the copy this tab holds, so
// the server can tell it to start over if the doc was rebuilt.
token: async () => {
- const ticket = ticketUsable(this.ticket) ? this.ticket : await api.createDocCollabTicket(this.docId);
+ const ticket = ticketUsable(this.ticket) ? this.ticket : await requestTicket(this.kind, this.docId);
this.ticket = null;
if (!ticket.enabled) throw new Error("live editing is off");
const epoch = this.ydoc.getMap("meta").get("epoch");
@@ -276,19 +302,34 @@ export class DocSession {
const next: DocCollaborator[] = [];
for (const [key, state] of this.provider.awareness?.getStates() ?? []) {
if (key === this.ydoc.clientID) continue;
- const u = (state as { user?: Partial<DocCollaborator> }).user;
+ const { user: u, cursor } = state as { user?: Partial<DocCollaborator>; cursor?: unknown };
if (!u?.name || !u.id) continue;
const dedupe = `${u.kind}:${u.id}`;
- if (seen.has(dedupe)) continue;
+ const editing = !!cursor;
+ if (seen.has(dedupe)) {
+ // The same person in two tabs is editing if either tab is.
+ if (editing) {
+ const index = next.findIndex((c) => `${c.kind}:${c.id}` === dedupe);
+ if (index >= 0 && !next[index]!.editing) next[index] = { ...next[index]!, key, editing };
+ }
+ continue;
+ }
seen.add(dedupe);
- next.push({ key, id: u.id, name: u.name, color: u.color ?? colorFor(u.id), kind: u.kind === "agent" ? "agent" : "member" });
+ next.push({ key, id: u.id, name: u.name, color: u.color ?? colorFor(u.id), kind: u.kind === "agent" ? "agent" : "member", editing });
}
- const signature = next.map((c) => `${c.key}:${c.kind}:${c.id}:${c.name}:${c.color}`).join("|");
+ const signature = next.map((c) => `${c.key}:${c.kind}:${c.id}:${c.name}:${c.color}:${c.editing}`).join("|");
if (signature === this.signature) return;
this.signature = signature;
this.update({ collaborators: next });
};
+ /** Calls `listener` on every awareness change, caret moves included. */
+ watchAwareness = (listener: () => void): (() => void) => {
+ const awareness = this.provider.awareness;
+ awareness?.on("change", listener);
+ return () => awareness?.off("change", listener);
+ };
+
/** Out of the cache: no page joins it again, and it ends with its last user. */
dropped = false;
@@ -336,7 +377,7 @@ export class DocSession {
/** Live sessions by server, doc and user, oldest first. */
const sessions = new Map<string, DocSession>();
-const sessionKey = (collabUrl: string, docId: string, userId: string) => `${collabUrl}\n${docId}\n${userId}`;
+const sessionKey = infoKey;
function dropSession(session: DocSession) {
if (sessions.get(session.key) === session) sessions.delete(session.key);
@@ -349,13 +390,19 @@ function dropSession(session: DocSession) {
* the saved state a recent `prefetchDocLive` brought, if any. Pair with
* `releaseDocSession`.
*/
-export function acquireDocSession(collabUrl: string, docId: string, userId: string, document: string): DocSession {
- const key = sessionKey(collabUrl, docId, userId);
+export function acquireDocSession(
+ collabUrl: string,
+ docId: string,
+ userId: string,
+ document: string,
+ kind: LiveKind = "doc",
+): DocSession {
+ const key = sessionKey(collabUrl, docId, userId, kind);
let session = sessions.get(key);
if (session) {
sessions.delete(key);
} else {
- session = new DocSession(key, collabUrl, docId, document, takeDocLive(collabUrl, docId, userId));
+ session = new DocSession(key, collabUrl, docId, document, takeDocLive(collabUrl, docId, userId, kind), kind);
}
sessions.set(key, session);
session.retain();
@@ -373,8 +420,13 @@ export function releaseDocSession(session: DocSession, opts: { discard?: boolean
}
/** The doc's live session, if one is open or kept. */
-export function findDocSession(collabUrl: string, docId: string, userId: string): DocSession | undefined {
- return sessions.get(sessionKey(collabUrl, docId, userId));
+export function findDocSession(
+ collabUrl: string,
+ docId: string,
+ userId: string,
+ kind: LiveKind = "doc",
+): DocSession | undefined {
+ return sessions.get(sessionKey(collabUrl, docId, userId, kind));
}
function base64ToBytes(base64: string): Uint8Array {
diff --git a/packages/views/docs/components/use-doc-collab.test.ts b/packages/views/docs/components/use-doc-collab.test.ts
new file mode 100644
index 0000000000..bed6439034
--- /dev/null
+++ b/packages/views/docs/components/use-doc-collab.test.ts
@@ -0,0 +1,104 @@
+import { renderHook } from "@testing-library/react";
+import { useLayoutEffect } from "react";
+import { describe, expect, it, vi } from "vitest";
+import * as Y from "yjs";
+import { locateCaret, useDocCollab } from "./use-doc-collab";
+import type { DocSession } from "./doc-live-session";
+
+vi.mock("@multica/core/realtime", () => ({ useWS: () => ({ collabUrl: "ws://collab" }) }));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (select: (s: unknown) => unknown) => select({ user: { id: "me", name: "Me", email: "me@x" } }),
+}));
+vi.mock("./doc-live-session", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./doc-live-session")>();
+ const state = { ready: true, synced: true, connected: true, collaborators: [], reset: false };
+ let id = 0;
+ return {
+ ...actual,
+ peekDocLive: (_url: string, docId: string) => ({ enabled: true, document: `issue:${docId}` }),
+ findDocSession: () => undefined,
+ acquireDocSession: (_url: string, _docId: string, _user: string, document: string) => ({
+ id: ++id,
+ document,
+ ydoc: new Y.Doc(),
+ provider: {},
+ subscribe: () => () => {},
+ getState: () => state,
+ watchAwareness: () => () => {},
+ }),
+ releaseDocSession: () => {},
+ };
+});
+
+function block(name: string, text: string, attrs: Record<string, string> = {}) {
+ const element = new Y.XmlElement(name);
+ for (const [key, value] of Object.entries(attrs)) element.setAttribute(key, value);
+ const content = new Y.XmlText();
+ content.insert(0, text);
+ element.insert(0, [content]);
+ return element;
+}
+
+/** A session whose one collaborator (key 7) has a caret `offset` characters into block `index`. */
+function sessionWithCaret(blocks: Y.XmlElement[], index: number | null, offset = 0) {
+ const ydoc = new Y.Doc();
+ const root = ydoc.getXmlFragment("default");
+ root.insert(0, blocks);
+ const states = new Map<number, unknown>();
+ if (index !== null) {
+ const text = (root.get(index) as Y.XmlElement).get(0) as Y.XmlText;
+ const head = Y.relativePositionToJSON(Y.createRelativePositionFromTypeIndex(text, offset));
+ states.set(7, { user: { id: "u", name: "U" }, cursor: { anchor: head, head } });
+ } else {
+ states.set(7, { user: { id: "u", name: "U" } });
+ }
+ return { ydoc, provider: { awareness: { getStates: () => states } } } as unknown as DocSession;
+}
+
+describe("locateCaret", () => {
+ const doc = () => [
+ block("paragraph", "Intro before any heading"),
+ block("heading", "Goals", { level: "2" }),
+ block("paragraph", "Ship by Q4"),
+ block("heading", "Risks", { level: "2" }),
+ block("paragraph", "The import API"),
+ ];
+
+ it("names the heading above the caret", () => {
+ expect(locateCaret(sessionWithCaret(doc(), 2, 3), 7)).toBe("Goals");
+ expect(locateCaret(sessionWithCaret(doc(), 4, 0), 7)).toBe("Risks");
+ });
+
+ it("names the heading the caret is in", () => {
+ expect(locateCaret(sessionWithCaret(doc(), 3, 2), 7)).toBe("Risks");
+ });
+
+ it("says nothing above the first heading, without a caret, or for someone unknown", () => {
+ expect(locateCaret(sessionWithCaret(doc(), 0, 1), 7)).toBeNull();
+ expect(locateCaret(sessionWithCaret(doc(), null), 7)).toBeNull();
+ expect(locateCaret(sessionWithCaret(doc(), 2), 8)).toBeNull();
+ });
+});
+
+describe("useDocCollab", () => {
+ it("never hands the next doc the previous doc's session", () => {
+ const seen: { docId: string; generation: number | null }[] = [];
+ const { rerender } = renderHook(
+ ({ docId }) => {
+ const state = useDocCollab(docId, "", "issue");
+ const generation = state.mode === "live" ? state.generation : null;
+ useLayoutEffect(() => {
+ seen.push({ docId, generation });
+ });
+ },
+ { initialProps: { docId: "a" } },
+ );
+ const first = seen.at(-1)?.generation;
+ expect(first).not.toBeNull();
+
+ rerender({ docId: "b" });
+ const afterSwitch = seen.slice(seen.findIndex((s) => s.docId === "b"));
+ expect(afterSwitch.some((s) => s.generation === first)).toBe(false);
+ expect(afterSwitch.at(-1)?.generation).not.toBeNull();
+ });
+});
diff --git a/packages/views/docs/components/use-doc-collab.ts b/packages/views/docs/components/use-doc-collab.ts
index eb4e102faf..f4f4ea9872 100644
--- a/packages/views/docs/components/use-doc-collab.ts
+++ b/packages/views/docs/components/use-doc-collab.ts
@@ -1,21 +1,24 @@
"use client";
-import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
+import * as Y from "yjs";
import { useAuthStore } from "@multica/core/auth";
import { configStore } from "@multica/core/config";
import { useWS } from "@multica/core/realtime";
import type { EditorCollaboration } from "../../editor/extensions";
-import { createDocumentCodec } from "../../editor/schema/codec";
+import { COLLAB_FIELD, createDocumentCodec } from "../../editor/schema/codec";
import {
acquireDocSession,
colorFor,
findDocSession,
liveEditingOff,
+ liveOffKey,
peekDocLive,
prefetchDocLive,
releaseDocSession,
type DocCollaborator,
type DocSession,
type DocSessionState,
+ type LiveKind,
} from "./doc-live-session";
export type { DocCollaborator };
@@ -45,6 +48,10 @@ export type DocCollabState =
collaborators: DocCollaborator[];
/** Changes the editor's key when the session starts over. */
generation: number;
+ /** The heading a collaborator's caret is under, if any. */
+ locate: (key: number) => string | null;
+ /** Calls back on every caret move, for views that show where people are. */
+ watchCarets: (listener: () => void) => () => void;
};
const IDLE_STATE: DocSessionState = { ready: false, synced: false, connected: false, collaborators: [], reset: false };
@@ -63,36 +70,96 @@ function editedContent(session: DocSession, base: string): string | null {
}
}
-export function useDocCollab(docId: string, content: string): DocCollabState {
+/** The text of the last heading at or above a collaborator's caret. */
+export function locateCaret(session: DocSession, key: number): string | null {
+ const cursor = (session.provider.awareness?.getStates().get(key) as { cursor?: { head?: unknown } } | undefined)?.cursor;
+ if (!cursor?.head) return null;
+ let position: Y.AbsolutePosition | null = null;
+ try {
+ position = Y.createAbsolutePositionFromRelativePosition(Y.createRelativePositionFromJSON(cursor.head), session.ydoc);
+ } catch {
+ return null;
+ }
+ if (!position) return null;
+ const root = session.ydoc.getXmlFragment(COLLAB_FIELD);
+ const blocks = root.toArray();
+ let index = position.index;
+ if (position.type !== root) {
+ let block: Y.AbstractType<unknown> | null = position.type;
+ while (block && block.parent !== root) block = block.parent as Y.AbstractType<unknown> | null;
+ if (!block) return null;
+ index = blocks.indexOf(block as (typeof blocks)[number]);
+ }
+ for (let i = Math.min(index, blocks.length - 1); i >= 0; i--) {
+ const block = blocks[i];
+ if (block instanceof Y.XmlElement && block.nodeName === "heading") {
+ const text = plainText(block).trim();
+ if (text) return text;
+ }
+ }
+ return null;
+}
+
+function plainText(node: Y.XmlElement | Y.XmlText | Y.XmlHook): string {
+ if (node instanceof Y.XmlText) {
+ return (node.toDelta() as { insert?: unknown }[]).map((d) => (typeof d.insert === "string" ? d.insert : "")).join("");
+ }
+ if (node instanceof Y.XmlElement) return node.toArray().map(plainText).join("");
+ return "";
+}
+
+/**
+ * The live session of a doc, or of an issue's description (`kind`). A host
+ * that stays mounted while `docId` changes gets a fresh state for each. With
+ * `enabled` false nothing is asked and the host edits solo, as for a guest.
+ */
+export function useDocCollab(
+ docId: string,
+ content: string,
+ kind: LiveKind = "doc",
+ enabled = true,
+): DocCollabState {
const { collabUrl } = useWS();
const user = useAuthStore((s) => s.user);
const userId = user?.id ?? "";
// A kept session or an answer fetched ahead of the page settles the mode
// without waiting.
- const [initial] = useState(() => {
- if (liveEditingOff.has(collabUrl)) return { mode: "solo" as const, document: null };
+ const settle = () => {
+ if (liveEditingOff.has(liveOffKey(collabUrl, kind))) return { mode: "solo" as const, document: null };
const document =
- findDocSession(collabUrl, docId, userId)?.document ??
+ findDocSession(collabUrl, docId, userId, kind)?.document ??
(() => {
- const ticket = peekDocLive(collabUrl, docId, userId);
+ const ticket = peekDocLive(collabUrl, docId, userId, kind);
return ticket?.enabled ? ticket.document : null;
})();
return document ? { mode: "live" as const, document } : { mode: "checking" as const, document: null };
- });
+ };
+ const [initial] = useState(settle);
const [mode, setMode] = useState<"checking" | "solo" | "live">(initial.mode);
const [document, setDocument] = useState<string | null>(initial.document);
const [carried, setCarried] = useState<string | null>(null);
- const [generation, setGeneration] = useState(0);
const [session, setSession] = useState<DocSession | null>(null);
+ const target = `${kind}:${docId}`;
+ const [settledTarget, setSettledTarget] = useState(target);
+ if (settledTarget !== target) {
+ const next = settle();
+ setSettledTarget(target);
+ setMode(next.mode);
+ setDocument(next.document);
+ setCarried(null);
+ // The previous doc's session stays in state until its effect cleans up.
+ setSession(null);
+ }
+ const [generation, setGeneration] = useState(0);
const [slow, setSlow] = useState(false);
const discard = useRef(false);
const contentRef = useRef(content);
contentRef.current = content;
useEffect(() => {
- if (mode !== "checking") return;
+ if (!enabled || mode !== "checking") return;
let cancelled = false;
- prefetchDocLive(collabUrl, docId, userId)
+ prefetchDocLive(collabUrl, docId, userId, kind)
.then((ticket) => {
if (cancelled) return;
setDocument(ticket.enabled ? ticket.document : null);
@@ -104,18 +171,18 @@ export function useDocCollab(docId: string, content: string): DocCollabState {
return () => {
cancelled = true;
};
- }, [mode, docId, collabUrl, userId]);
+ }, [enabled, mode, docId, collabUrl, userId, kind]);
useEffect(() => {
- if (mode !== "live" || !document || !userId) return;
- const next = acquireDocSession(collabUrl, docId, userId, document);
+ if (!enabled || mode !== "live" || !document || !userId) return;
+ const next = acquireDocSession(collabUrl, docId, userId, document, kind);
discard.current = false;
setSession(next);
return () => {
releaseDocSession(next, { discard: discard.current });
setSession(null);
};
- }, [mode, document, docId, collabUrl, userId, generation]);
+ }, [enabled, mode, document, docId, collabUrl, userId, generation, kind]);
const state = useSyncExternalStore(session?.subscribe ?? noSubscribe, session?.getState ?? idleState);
@@ -147,6 +214,9 @@ export function useDocCollab(docId: string, content: string): DocCollabState {
};
}, [session, user]);
+ const locate = useCallback((key: number) => (session ? locateCaret(session, key) : null), [session]);
+
+ if (!enabled) return { mode: "solo" };
if (mode === "solo") return { mode, carried };
// A reset session is about to be replaced; nothing may keep editing it.
if (mode === "checking" || !collaboration || !session || state.reset) return { mode: "checking" };
@@ -159,5 +229,7 @@ export function useDocCollab(docId: string, content: string): DocCollabState {
collaboration,
collaborators: state.collaborators,
generation: session.id,
+ locate,
+ watchCarets: session.watchAwareness,
};
}
diff --git a/packages/views/editor/extensions/collaboration-caret-restore.test.ts b/packages/views/editor/extensions/collaboration-caret-restore.test.ts
new file mode 100644
index 0000000000..1e3303c01e
--- /dev/null
+++ b/packages/views/editor/extensions/collaboration-caret-restore.test.ts
@@ -0,0 +1,58 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { Editor } from "@tiptap/core";
+import StarterKit from "@tiptap/starter-kit";
+import Collaboration from "@tiptap/extension-collaboration";
+import * as Y from "yjs";
+
+// Covers patches/@[email protected]: drop the patch only once an
+// upgraded @tiptap/y-tiptap passes this on its own.
+
+let editor: Editor | null = null;
+afterEach(() => {
+ editor?.destroy();
+ editor = null;
+ document.body.innerHTML = "";
+});
+
+function setup() {
+ const shared = new Y.Doc();
+ const fragment = shared.getXmlFragment("default");
+ const paragraph = (text: string) => {
+ const p = new Y.XmlElement("paragraph");
+ p.insert(0, [new Y.XmlText(text)]);
+ return p;
+ };
+ fragment.insert(0, [paragraph("First"), paragraph("Second"), paragraph("Third")]);
+ const local = new Y.Doc();
+ Y.applyUpdate(local, Y.encodeStateAsUpdate(shared));
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ editor = new Editor({
+ element,
+ extensions: [StarterKit.configure({ undoRedo: false }), Collaboration.configure({ document: local })],
+ });
+ return { editor, local };
+}
+
+describe("caret restore after a collaborator's change", () => {
+ it("keeps the caret in its own new paragraph when a collaborator opens one above it", () => {
+ const { editor, local } = setup();
+ // Enter at the end of "Third": the caret sits in a fresh empty paragraph.
+ editor.commands.focus("end");
+ editor.commands.splitBlock();
+ expect(editor.state.selection.$from.index(0)).toBe(3);
+
+ // Meanwhile a collaborator presses Enter at the end of "First".
+ const remote = new Y.Doc();
+ Y.applyUpdate(remote, Y.encodeStateAsUpdate(local));
+ const before = Y.encodeStateVector(remote);
+ remote.getXmlFragment("default").insert(1, [new Y.XmlElement("paragraph")]);
+ Y.applyUpdate(local, Y.encodeStateAsUpdate(remote, before), "remote");
+
+ expect(editor.state.doc.childCount).toBe(5);
+ expect(editor.state.selection.$from.index(0)).toBe(4);
+ editor.commands.insertContent("mine");
+ expect(editor.state.doc.child(1).textContent).toBe("");
+ expect(editor.state.doc.child(4).textContent).toBe("mine");
+ });
+});
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 942b6cdf1b..0fb097f469 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -291,6 +291,7 @@ function renderCaret(user: Record<string, string>): HTMLElement {
const caret = document.createElement("span");
caret.classList.add("collaboration-carets__caret");
caret.setAttribute("aria-hidden", "true");
+ if (user.id) caret.dataset.collaborator = `${user.kind ?? "member"}:${user.id}`;
caret.style.borderColor = user.color ?? "";
const label = document.createElement("div");
label.classList.add("collaboration-carets__label");
diff --git a/packages/views/issues/components/issue-agent-header-chip.tsx b/packages/views/issues/components/issue-agent-header-chip.tsx
index 7d64386a6b..12b3a81ae1 100644
--- a/packages/views/issues/components/issue-agent-header-chip.tsx
+++ b/packages/views/issues/components/issue-agent-header-chip.tsx
@@ -166,87 +166,82 @@ function ActiveChip({
);
return (
- <div className="flex items-center gap-1">
- <Popover open={open} onOpenChange={setOpen}>
- {/* Hover opens the card so the live activity reads as a glanceable
- status surface, not a click target. In Base UI the hover config
- lives on the Trigger (a popover can have multiple triggers), not
- the Root. The trigger stays a real button, so click and keyboard
- (Enter/Space) still toggle it for touch and a11y. A short open
- delay avoids flicker when the pointer merely passes over the chip;
- the close delay keeps it open while the pointer travels across the
- hover bridge into the interactive rows. */}
- <PopoverTrigger
- openOnHover
- delay={150}
- closeDelay={200}
- render={
- <button
- type="button"
- aria-label={label}
- // While an agent is actively running, the chip wears the
- // brand border beam — a highlight sweeping around its rounded
- // edge — so a triggered run is unmistakably "alive" in the
- // header. Queued-only state stays calm (no beam) to reserve the
- // motion for work that is genuinely in flight.
- className={cn(
- "flex h-9 min-w-9 max-w-[11rem] items-center justify-center gap-1.5 rounded-md px-2 text-muted-foreground outline-none transition-colors hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring md:h-7 md:min-w-0 md:justify-start md:px-1.5",
- anyRunning && "relative bg-brand/5",
- )}
- />
- }
- >
- <AgentAvatarStack
- agentIds={agentIds}
- size="sm"
- max={3}
- opacity={anyRunning ? "full" : "half"}
- />
- <span
+ <Popover open={open} onOpenChange={setOpen}>
+ {/* Hover opens the card so the live activity reads as a glanceable
+ status surface, not a click target. In Base UI the hover config
+ lives on the Trigger (a popover can have multiple triggers), not
+ the Root. The trigger stays a real button, so click and keyboard
+ (Enter/Space) still toggle it for touch and a11y. A short open
+ delay avoids flicker when the pointer merely passes over the chip;
+ the close delay keeps it open while the pointer travels across the
+ hover bridge into the interactive rows. */}
+ <PopoverTrigger
+ openOnHover
+ delay={150}
+ closeDelay={200}
+ render={
+ <button
+ type="button"
+ aria-label={label}
+ // While an agent is actively running, the chip wears the
+ // brand border beam — a highlight sweeping around its rounded
+ // edge — so a triggered run is unmistakably "alive" in the
+ // header. Queued-only state stays calm (no beam) to reserve the
+ // motion for work that is genuinely in flight.
className={cn(
- "hidden min-w-0 truncate text-caption md:inline",
- anyRunning ? "text-info" : "text-muted-foreground",
- )}
- >
- {label}
- </span>
- {anyRunning && <BorderBeam />}
- </PopoverTrigger>
- <PopoverContent align="end" keepMounted className="w-80">
- <div className="text-caption font-medium text-muted-foreground">
- {t(
- ($) =>
- anyRunning
- ? $.agent_activity.hover_header
- : $.agent_activity.hover_header_queued,
- { count: agentIds.length },
+ "flex h-9 min-w-9 max-w-[11rem] items-center justify-center gap-1.5 rounded-md px-2 text-muted-foreground outline-none transition-colors hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring md:h-7 md:min-w-0 md:justify-start md:px-1.5",
+ anyRunning && "relative bg-brand/5",
)}
- </div>
- <div className="flex flex-col gap-0.5">
- {activeTasks.map((task) => (
- <ActiveTaskRow
- key={task.id}
- task={task}
- issueId={issueId}
- onJump={
- onJumpToRun
- ? () => {
- setOpen(false);
- onJumpToRun(task.id);
- }
- : undefined
- }
- onTranscriptOpenChange={(open, fromKeyboard) => {
- onTranscriptOpenChange(task, open, fromKeyboard === true);
- }}
- />
- ))}
- </div>
- </PopoverContent>
- </Popover>
- {/* Separator from the action buttons — the chip is a status segment,
- not another button, so a hairline keeps the two groups legible. */}
- <span className="h-4 w-px bg-border" aria-hidden="true" />
- </div>
+ />
+ }
+ >
+ <AgentAvatarStack
+ agentIds={agentIds}
+ size="sm"
+ max={3}
+ opacity={anyRunning ? "full" : "half"}
+ />
+ <span
+ className={cn(
+ "hidden min-w-0 truncate text-caption md:inline",
+ anyRunning ? "text-info" : "text-muted-foreground",
+ )}
+ >
+ {label}
+ </span>
+ {anyRunning && <BorderBeam />}
+ </PopoverTrigger>
+ <PopoverContent align="end" keepMounted className="w-80">
+ <div className="text-caption font-medium text-muted-foreground">
+ {t(
+ ($) =>
+ anyRunning
+ ? $.agent_activity.hover_header
+ : $.agent_activity.hover_header_queued,
+ { count: agentIds.length },
+ )}
+ </div>
+ <div className="flex flex-col gap-0.5">
+ {activeTasks.map((task) => (
+ <ActiveTaskRow
+ key={task.id}
+ task={task}
+ issueId={issueId}
+ onJump={
+ onJumpToRun
+ ? () => {
+ setOpen(false);
+ onJumpToRun(task.id);
+ }
+ : undefined
+ }
+ onTranscriptOpenChange={(open, fromKeyboard) => {
+ onTranscriptOpenChange(task, open, fromKeyboard === true);
+ }}
+ />
+ ))}
+ </div>
+ </PopoverContent>
+ </Popover>
);
}
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 4fc88244bd..32af0b4358 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -22,12 +22,6 @@ import { useIssueSidebarSectionsStore } from "@multica/core/issues/stores/issue-
import { useSubIssuesCollapseStore } from "@multica/core/issues/stores/sub-issues-collapse-store";
import { configureShortcutPlatform } from "@multica/core/shortcuts";
-vi.mock("./issue-wakeup-header-chip", () => ({
- IssueWakeupHeaderChip: ({ onOpen }: { onOpen: () => void }) => (
- <button type="button" onClick={onOpen}>Review open wakeups</button>
- ),
-}));
-
const TEST_RESOURCES = { en: { agents: enAgents, common: enCommon, inbox: enInbox, issues: enIssues } };
const mockViewport = vi.hoisted(() => ({ isMobile: false }));
@@ -375,6 +369,7 @@ const mockApiObj = vi.hoisted(() => ({
getProject: vi.fn(),
listProjects: vi.fn().mockResolvedValue({ projects: [] }),
listPins: vi.fn().mockResolvedValue([]),
+ createIssueCollabTicket: vi.fn().mockResolvedValue({ enabled: false }),
}));
vi.mock("@multica/core/api", () => ({
@@ -867,65 +862,6 @@ describe("IssueDetail (shared)", () => {
useIssueSidebarSectionsStore.getState().reset();
});
- describe("sidebar section settings", () => {
- const wakeupsSlot = (container: HTMLElement) => container.querySelector('[data-issue-sidebar-section="wakeups"]');
- const wakeupsSwitch = async () => {
- fireEvent.click(screen.getByRole("button", { name: "Customize sidebar" }));
- return within(await screen.findByRole("dialog")).getByRole("switch", { name: "Wakeups" });
- };
-
- it("hides wakeups from settings after the header chip opened them", async () => {
- const { container } = renderIssueDetail();
- fireEvent.click(await screen.findByRole("button", { name: "Review open wakeups" }));
- expect(wakeupsSlot(container)).not.toBeNull();
-
- fireEvent.click(await wakeupsSwitch());
- expect(useIssueSidebarSectionsStore.getState().hidden).toContain("wakeups");
- expect(wakeupsSlot(container)).toBeNull();
- });
-
- it("lets settings hide again the wakeups the header chip revealed", async () => {
- useIssueSidebarSectionsStore.getState().setHidden("wakeups", true);
- const { container } = renderIssueDetail();
- fireEvent.click(await screen.findByRole("button", { name: "Review open wakeups" }));
- expect(wakeupsSlot(container)).not.toBeNull();
- expect(useIssueSidebarSectionsStore.getState().hidden).toContain("wakeups");
-
- const toggle = await wakeupsSwitch();
- fireEvent.click(toggle);
- expect(useIssueSidebarSectionsStore.getState().hidden).not.toContain("wakeups");
- fireEvent.click(toggle);
- expect(useIssueSidebarSectionsStore.getState().hidden).toContain("wakeups");
- expect(wakeupsSlot(container)).toBeNull();
- });
-
- it("ends the header chip's reveal when the reader moves to another issue", async () => {
- useIssueSidebarSectionsStore.getState().setHidden("wakeups", true);
- const issue2 = { ...mockIssue, id: "issue-2", title: "Second issue", description: "Second description" };
- mockApiObj.getIssue.mockImplementation((issueId: string) =>
- Promise.resolve(issueId === "issue-2" ? issue2 : mockIssue),
- );
- const queryClient = createTestQueryClient();
- queryClient.setQueryData(["issues", "ws-1", "detail", "issue-2"], issue2);
- const ui = (issueId: string) => (
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <QueryClientProvider client={queryClient}>
- <IssueDetail issueId={issueId} />
- </QueryClientProvider>
- </I18nProvider>
- );
- const { container, rerender } = render(ui("issue-1"));
- fireEvent.click(await screen.findByRole("button", { name: "Review open wakeups" }));
- expect(wakeupsSlot(container)).not.toBeNull();
-
- rerender(ui("issue-2"));
- await screen.findByDisplayValue("Second description");
- rerender(ui("issue-1"));
- await screen.findByDisplayValue("Add JWT auth to the backend");
- expect(wakeupsSlot(container)).toBeNull();
- });
- });
-
it("passes the issue's agent assignment to the local-directory hint", async () => {
const agent = { id: "agent-vue", name: "Vue developer", runtime_id: "runtime-vue" };
mockApiObj.getIssue.mockResolvedValue({
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 7ae87ede8d..89fb16d05a 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -45,6 +45,7 @@ import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@multica/u
import { Sheet, SheetContent } from "@multica/ui/components/ui/sheet";
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
import { StorageLimitNotice } from "../../billing/storage-limit-notice";
+import { useDocCollab, type DocCollaborator } from "../../docs/components/use-doc-collab";
import { ContentEditor, ReadonlyContent, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useEditorUpload, PreviewSequenceProvider, collectPreviewSequence, ImageThumbnailsProvider } from "../../editor";
import {
WAKEUP_ACTIVITY_ACTIONS,
@@ -122,7 +123,7 @@ import { ResolvedThreadBar } from "./resolved-thread-bar";
import { ThreadMinimap, type ThreadMinimapThread } from "./thread-minimap";
import { collectThreadParticipants, collectThreadReplies, deriveThreadResolution } from "./thread-utils";
import { IssueAgentHeaderChip } from "./issue-agent-header-chip";
-import { IssueWakeupHeaderChip } from "./issue-wakeup-header-chip";
+import { IssuePresenceHeaderChip } from "./issue-presence-header-chip";
import { ExecutionLogSection } from "./execution-log-section";
import { WakeupsSection } from "./wakeups-section";
import { QuickActionsSection } from "./quick-actions-section";
@@ -1446,8 +1447,6 @@ export function IssueLoadError({
// Loading skeleton
const ISSUE_DETAIL_LAYOUT_ID = "multica_issue_detail_layout";
-const REVEALED_WAKEUPS: readonly IssueSidebarSection[] = ["wakeups"];
-
/**
* Exported so `IssueDetailRoute` can show the identical frame while it resolves
* an identifier URL to its issue — the two waits are indistinguishable to the
@@ -3061,6 +3060,47 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
setDescPendingAttachments([]);
}, [id]);
+ // With live editing on, the description is a shared document that the
+ // collaboration service saves. The solo editor still shows first, so the
+ // page never waits on that answer and works as before when live editing is
+ // off; the live editor takes over once it is ready, though not while
+ // someone is in the solo one. Unmounting the solo editor flushes its
+ // pending save, which the server merges into the live document.
+ const descCollab = useDocCollab(id, issue?.description ?? "", "issue", !guest);
+ const descLive = descCollab.mode === "live" ? descCollab : null;
+ const [descLiveReadyFor, setDescLiveReadyFor] = useState<number | null>(null);
+ const [descSoloHeld, setDescSoloHeld] = useState(false);
+ useEffect(() => setDescSoloHeld(false), [id]);
+ const showLiveDesc = !!descLive?.ready && descLiveReadyFor === descLive.generation && !descSoloHeld;
+ const descContentRef = useRef<HTMLDivElement>(null);
+ const descPresence = useMemo(
+ () => descLive?.collaborators.filter((c) => !(c.kind === "member" && c.id === user?.id)) ?? [],
+ [descLive?.collaborators, user?.id],
+ );
+ const jumpToCollaborator = useCallback((c: DocCollaborator) => {
+ const caret = descContentRef.current?.querySelector<HTMLElement>(
+ `.collaboration-carets__caret[data-collaborator="${CSS.escape(`${c.kind}:${c.id}`)}"]`,
+ );
+ caret?.scrollIntoView({ block: "center", behavior: "smooth" });
+ }, []);
+ const descCarried = descCollab.mode === "solo" ? (descCollab.carried ?? null) : null;
+ const queueDescriptionSaveRef = useRef<
+ ((draft: { markdown: string; baseMarkdown: string; attachmentIds: string[] }) => void) | null
+ >(null);
+ useEffect(() => {
+ // Typed into a live session that never connected: save it as a solo edit.
+ if (descCarried === null) return;
+ queueDescriptionSaveRef.current?.({
+ markdown: descCarried,
+ baseMarkdown: issue?.description ?? "",
+ attachmentIds: descPendingAttachmentsRef.current
+ .filter((a) => contentReferencesAttachment(descCarried, a))
+ .map((a) => a.id),
+ });
+ // Once per carried draft; the issue is read as it is then.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [descCarried]);
+
// Shared issue actions (mutations, pin, copy-link, modal dispatch, etc.).
// Called before the `if (!issue)` early return so hook order stays stable.
const actions = useIssueActions(issue);
@@ -3192,22 +3232,6 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
});
}, [beginDesktopSidebarToggle, isMobile, sidebarRef]);
- // The header's wakeup chip opens the sidebar and brings the Wakeups section
- // into view with focus on its heading, showing it on this issue even when
- // the reader hid it from the sidebar. The reveal lasts until the reader
- // switches the section in settings or moves to another issue.
- const [revealedWakeupsFor, setRevealedWakeupsFor] = useState<string | null>(null);
- if (revealedWakeupsFor !== null && revealedWakeupsFor !== id) setRevealedWakeupsFor(null);
- const openWakeups = useCallback(() => {
- setRevealedWakeupsFor(id);
- if (!sidebarOpen) handleToggleSidebar();
- window.requestAnimationFrame(() => {
- const heading = document.getElementById(`issue-wakeups-${id}`);
- heading?.scrollIntoView({ block: "nearest" });
- heading?.focus({ preventScroll: true });
- });
- }, [handleToggleSidebar, id, sidebarOpen]);
-
useRightSidebarShortcut(rightSidebarShortcutTargetRef, handleToggleSidebar);
useIssueDetailScrollRestore({
@@ -3309,6 +3333,7 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
}
persistDescriptionSave(draft);
};
+ queueDescriptionSaveRef.current = queueDescriptionSave;
const canAddProperty = OPTIONAL_PROP_KEYS.some(
(key) => !visibleOptionalProps.has(key) && (key !== "stage" || issue.parent_issue_id != null),
@@ -3741,8 +3766,6 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
? GUEST_SIDEBAR_SECTIONS.has(section)
: (section !== "pull_requests" || githubSettings.prSidebar) && (section !== "plugins" || pluginsEnabled),
)}
- revealed={revealedWakeupsFor === id ? REVEALED_WAKEUPS : undefined}
- onRevealEnd={() => setRevealedWakeupsFor(null)}
/>
);
@@ -3905,6 +3928,7 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
/>
)}
<BreadcrumbHeader
+ className="@container/issue-header"
leading={leadingAction}
segments={breadcrumbSegments}
leaf={
@@ -3924,11 +3948,23 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
}
actions={
<>
- {/* Live "agent is working" chip, leftmost in the right cluster so
- it never overlaps the title (which truncates to make room).
- It self-hides when no agent is active. */}
- {!guest && <IssueAgentHeaderChip issueId={id} onJumpToRun={jumpToRun} />}
- {!guest && <IssueWakeupHeaderChip issueId={id} onOpen={openWakeups} />}
+ {/* What is happening on the issue right now, left of the actions:
+ who else has it open, then which agent is working. Each chip
+ hides itself when there is nothing to say; the hairline before
+ the actions shows only while one of them does. */}
+ {!guest && (
+ <div className="flex items-center gap-1 empty:hidden after:ml-1 after:h-4 after:w-px after:bg-border">
+ {descLive && (
+ <IssuePresenceHeaderChip
+ collaborators={descPresence}
+ locate={descLive.locate}
+ watchCarets={descLive.watchCarets}
+ onJump={jumpToCollaborator}
+ />
+ )}
+ <IssueAgentHeaderChip issueId={id} onJumpToRun={jumpToRun} />
+ </div>
+ )}
{!guest && <IssueDetailActionsDropdown
issue={issue}
locateInSidebar={!isPeek}
@@ -4192,18 +4228,37 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
if (!descriptionEditingRef.current) {
descriptionEditingRef.current = true;
}
+ if (!showLiveDesc) setDescSoloHeld(true);
}}
onBlurCapture={(event) => {
if (!event.currentTarget.contains(event.relatedTarget)) {
descriptionEditingRef.current = false;
+ setDescSoloHeld(false);
}
}}
>
{descriptionAnnotations.popup}
- <div data-comment-content={descriptionSourceId}>
+ <div ref={descContentRef} data-comment-content={descriptionSourceId}>
{guest ? (
<ReadonlyContent content={issue.description ?? ""} attachments={descEditorAttachments} />
) : (
+ <>
+ {descLive?.ready && (
+ <div hidden={!showLiveDesc}>
+ <ContentEditor
+ ref={showLiveDesc ? descEditorRef : undefined}
+ key={`${id}:${descLive.generation}`}
+ collaboration={descLive.collaboration}
+ onReady={() => setDescLiveReadyFor(descLive.generation)}
+ placeholder={t(($) => $.detail.desc_placeholder)}
+ onUploadFile={handleDescriptionUpload}
+ currentIssueId={id}
+ selectionAction={descriptionSelectionAction}
+ attachments={descEditorAttachments}
+ />
+ </div>
+ )}
+ {!showLiveDesc && (
<ContentEditor
ref={descEditorRef}
key={id}
@@ -4247,6 +4302,8 @@ export function IssueDetail({ issueId, onDelete, onArchive, onUnsubscribeArchive
attachments={descEditorAttachments}
/>
)}
+ </>
+ )}
</div>
{descStorageRefusal && (
<StorageLimitNotice
diff --git a/packages/views/issues/components/issue-presence-header-chip.test.tsx b/packages/views/issues/components/issue-presence-header-chip.test.tsx
new file mode 100644
index 0000000000..36a3219e48
--- /dev/null
+++ b/packages/views/issues/components/issue-presence-header-chip.test.tsx
@@ -0,0 +1,86 @@
+// @vitest-environment jsdom
+
+import { act, fireEvent, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import type { DocCollaborator } from "../../docs/components/use-doc-collab";
+import { renderWithI18n } from "../../test/i18n";
+import { IssuePresenceHeaderChip } from "./issue-presence-header-chip";
+
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: ({ name }: { name: string }) => <span data-testid="avatar">{name}</span>,
+}));
+
+const person = (key: number, name: string, editing = false): DocCollaborator => ({
+ key,
+ id: `user-${key}`,
+ name,
+ color: "#db2777",
+ kind: "member",
+ editing,
+});
+
+function renderChip(collaborators: DocCollaborator[], sections: Record<number, string> = {}) {
+ const onJump = vi.fn();
+ let move: (() => void) | null = null;
+ const watchCarets = vi.fn((listener: () => void) => {
+ move = listener;
+ return () => {
+ move = null;
+ };
+ });
+ const view = renderWithI18n(
+ <IssuePresenceHeaderChip
+ collaborators={collaborators}
+ locate={(key) => sections[key] ?? null}
+ watchCarets={watchCarets}
+ onJump={onJump}
+ />,
+ );
+ return { ...view, onJump, watchCarets, move: () => move?.() };
+}
+
+describe("IssuePresenceHeaderChip", () => {
+ it("renders nothing when the reader is alone", () => {
+ const { container } = renderChip([]);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("shows up to three people, editors first, and how many are here", () => {
+ renderChip([person(1, "Ann"), person(2, "Bo", true), person(3, "Cy"), person(4, "Di")]);
+ const chip = screen.getByRole("button", { name: "4 viewing" });
+ expect([...chip.querySelectorAll("[data-testid=avatar]")].map((a) => a.textContent)).toEqual(["Bo", "Ann", "Cy"]);
+ });
+
+ it("lists editors with their section and jumps to the one clicked", async () => {
+ const sections: Record<number, string> = { 2: "Goals" };
+ const { onJump, watchCarets, move } = renderChip([person(1, "Ann"), person(2, "Bo", true)], sections);
+ expect(watchCarets).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "2 viewing" }));
+
+ expect(await screen.findByText("Editing · 1")).toBeInTheDocument();
+ expect(screen.getByText("Viewing · 1")).toBeInTheDocument();
+ expect(screen.getByText('In "Goals"')).toBeInTheDocument();
+ expect(watchCarets).toHaveBeenCalledTimes(1);
+
+ // An open list follows the editor to another section.
+ sections[2] = "Risks";
+ await act(async () => {
+ move();
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
+ });
+ expect(screen.getByText('In "Risks"')).toBeInTheDocument();
+
+ const row = document.querySelector<HTMLElement>('[data-presence-row="Bo"]')!;
+ fireEvent.click(row);
+ expect(onJump).toHaveBeenCalledWith(expect.objectContaining({ key: 2, name: "Bo" }));
+ });
+
+ it("names the viewers past the listed ones instead of listing them", async () => {
+ const names = ["Ann", "Bo", "Cy", "Di", "Ed", "Fay", "Gus", "Hal", "Ivy", "Jo", "Kai", "Lu"];
+ renderChip(names.map((name, i) => person(i + 1, name)));
+ fireEvent.click(screen.getByRole("button", { name: "12 viewing" }));
+ expect(await screen.findByText("6 more: Gus, Hal, Ivy, Jo...")).toBeInTheDocument();
+ expect(document.querySelectorAll("[data-presence-row]")).toHaveLength(6);
+ expect(screen.queryByText("Click a name to jump to their cursor")).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/issues/components/issue-presence-header-chip.tsx b/packages/views/issues/components/issue-presence-header-chip.tsx
new file mode 100644
index 0000000000..31698aa583
--- /dev/null
+++ b/packages/views/issues/components/issue-presence-header-chip.tsx
@@ -0,0 +1,182 @@
+"use client";
+
+import { memo, useEffect, useReducer, useState, type CSSProperties, type ReactNode } from "react";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@multica/ui/components/ui/popover";
+import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "../../common/actor-avatar";
+import type { DocCollaborator } from "../../docs/components/use-doc-collab";
+import { useT } from "../../i18n";
+
+/** Heads shown in the chip; a narrow header shows one fewer. */
+const HEADS = 3;
+/** People listed under "Viewing" before the rest are only named. */
+const LISTED_VIEWERS = 6;
+/** Names after the listed viewers, before the list ends in an ellipsis. */
+const NAMED_REST = 4;
+
+/**
+ * Who else has the issue open, in the issue header beside the agent chip.
+ * People with a caret in the description come first, ringed in their caret's
+ * colour so the chip matches the carets in the text. Hovering lists everyone,
+ * the editors with the section they are in; clicking an editor scrolls to
+ * their caret. Renders nothing when the reader is alone.
+ */
+export const IssuePresenceHeaderChip = memo(function IssuePresenceHeaderChip({
+ collaborators,
+ locate,
+ watchCarets,
+ onJump,
+}: {
+ /** Everyone but the reader. */
+ collaborators: readonly DocCollaborator[];
+ locate: (key: number) => string | null;
+ watchCarets: (listener: () => void) => () => void;
+ onJump: (collaborator: DocCollaborator) => void;
+}) {
+ const { t } = useT("issues");
+ const [open, setOpen] = useState(false);
+ // Where each editor is changes with every caret move; only an open list
+ // follows it.
+ const [, refresh] = useReducer((n: number) => n + 1, 0);
+ useEffect(() => {
+ if (!open) return;
+ let frame = 0;
+ const stop = watchCarets(() => {
+ if (frame) return;
+ frame = requestAnimationFrame(() => {
+ frame = 0;
+ refresh();
+ });
+ });
+ return () => {
+ stop();
+ cancelAnimationFrame(frame);
+ };
+ }, [open, watchCarets]);
+
+ if (collaborators.length === 0) return null;
+ const editing = collaborators.filter((c) => c.editing);
+ const viewing = collaborators.filter((c) => !c.editing);
+ const ordered = [...editing, ...viewing];
+ const label = t(($) => $.presence.viewing, { count: collaborators.length });
+ const rest = viewing.slice(LISTED_VIEWERS);
+ const separator = t(($) => $.presence.name_separator);
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger
+ openOnHover
+ delay={150}
+ closeDelay={200}
+ render={
+ <button
+ type="button"
+ aria-label={label}
+ className="flex h-9 min-w-9 items-center justify-center gap-1.5 rounded-md px-2 text-muted-foreground outline-none transition-colors hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring md:h-7 md:min-w-0 md:justify-start md:px-1.5"
+ />
+ }
+ >
+ <span className="inline-flex items-center">
+ {ordered.slice(0, HEADS).map((c, i) => (
+ <span
+ key={c.key}
+ className={cn(
+ "inline-flex rounded-full ring-2",
+ !c.editing && "ring-background",
+ i > 0 && "-ml-1",
+ i === HEADS - 1 && "@max-[40rem]/issue-header:hidden",
+ )}
+ style={c.editing ? ({ "--tw-ring-color": c.color } as CSSProperties) : undefined}
+ >
+ <ActorAvatar actorType={c.kind} actorId={c.id} name={c.name} size="sm" profileLink={false} />
+ </span>
+ ))}
+ </span>
+ <span className="whitespace-nowrap text-caption @max-[40rem]/issue-header:hidden">{label}</span>
+ <span className="hidden text-caption tabular-nums @max-[40rem]/issue-header:inline">
+ {collaborators.length}
+ </span>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="max-h-(--available-height) w-72 overflow-y-auto">
+ {editing.length > 0 && (
+ <PresenceGroup title={t(($) => $.presence.editing)} count={editing.length}>
+ {editing.map((c) => {
+ const section = locate(c.key);
+ return (
+ <button
+ key={c.key}
+ type="button"
+ data-presence-row={c.name}
+ className="flex items-center gap-2 rounded-md px-1.5 py-1 text-left outline-none hover:bg-accent/60 focus-visible:bg-accent/60"
+ onClick={() => {
+ setOpen(false);
+ onJump(c);
+ }}
+ >
+ <PresenceAvatar collaborator={c} />
+ <span className="min-w-0 flex-1 truncate text-foreground">{c.name}</span>
+ {section && (
+ <span className="min-w-0 max-w-[50%] shrink-0 truncate text-caption text-muted-foreground">
+ {t(($) => $.presence.where, { section })}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </PresenceGroup>
+ )}
+ {viewing.length > 0 && (
+ <PresenceGroup title={t(($) => $.presence.watching)} count={viewing.length}>
+ {viewing.slice(0, LISTED_VIEWERS).map((c) => (
+ <div key={c.key} data-presence-row={c.name} className="flex items-center gap-2 px-1.5 py-1">
+ <PresenceAvatar collaborator={c} />
+ <span className="min-w-0 flex-1 truncate text-foreground">{c.name}</span>
+ </div>
+ ))}
+ {rest.length > 0 && (
+ <div className="px-1.5 pt-1 text-caption text-muted-foreground">
+ {t(($) => $.presence.more, {
+ count: rest.length,
+ names:
+ rest.slice(0, NAMED_REST).map((c) => c.name).join(separator) +
+ (rest.length > NAMED_REST ? "..." : ""),
+ })}
+ </div>
+ )}
+ </PresenceGroup>
+ )}
+ {editing.length > 0 && (
+ <div className="border-t border-border px-1.5 pt-2 text-caption text-muted-foreground">
+ {t(($) => $.presence.jump_hint)}
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ );
+});
+
+function PresenceGroup({ title, count, children }: { title: string; count: number; children: ReactNode }) {
+ return (
+ <div className="flex flex-col gap-0.5">
+ <div className="px-1.5 text-caption font-medium text-muted-foreground">
+ {title} · {count}
+ </div>
+ {children}
+ </div>
+ );
+}
+
+function PresenceAvatar({ collaborator: c }: { collaborator: DocCollaborator }) {
+ return (
+ <span
+ className={cn("inline-flex shrink-0 rounded-full ring-2", !c.editing && "ring-background")}
+ style={c.editing ? ({ "--tw-ring-color": c.color } as CSSProperties) : undefined}
+ >
+ <ActorAvatar actorType={c.kind} actorId={c.id} name={c.name} size="sm" profileLink={false} />
+ </span>
+ );
+}
diff --git a/packages/views/issues/components/issue-sidebar-settings.test.tsx b/packages/views/issues/components/issue-sidebar-settings.test.tsx
index 3d0ef0e351..568262040d 100644
--- a/packages/views/issues/components/issue-sidebar-settings.test.tsx
+++ b/packages/views/issues/components/issue-sidebar-settings.test.tsx
@@ -18,10 +18,10 @@ const sections = Object.fromEntries(
) as Record<IssueSidebarSection, React.ReactNode>;
const available = ISSUE_SIDEBAR_SECTIONS.filter((id) => id !== "plugins");
-function renderSections(revealed?: IssueSidebarSection[]) {
+function renderSections() {
return render(
<I18nProvider resources={TEST_RESOURCES} locale="en">
- <IssueSidebarSections sections={sections} available={available} revealed={revealed} />
+ <IssueSidebarSections sections={sections} available={available} />
</I18nProvider>,
);
}
@@ -54,13 +54,6 @@ describe("IssueSidebarSections", () => {
expect(screen.getByRole("button", { name: /2 sections hidden/ })).toBeInTheDocument();
});
- it("shows a hidden section the reader jumped to", () => {
- act(() => useIssueSidebarSectionsStore.getState().setHidden("wakeups", true));
- renderSections(["wakeups"]);
- expect(screen.getByText("body:wakeups")).toBeInTheDocument();
- expect(screen.queryByRole("button", { name: /hidden/ })).toBeNull();
- });
-
it("lists the available sections, marks the empty and locked ones, and hides on toggle", async () => {
renderSections();
const dialog = await openSettings();
diff --git a/packages/views/issues/components/issue-sidebar-settings.tsx b/packages/views/issues/components/issue-sidebar-settings.tsx
index cebe22ef9d..a847b27688 100644
--- a/packages/views/issues/components/issue-sidebar-settings.tsx
+++ b/packages/views/issues/components/issue-sidebar-settings.tsx
@@ -75,29 +75,17 @@ export function useIssueSidebarSectionLabels(): Record<IssueSidebarSection, stri
export function IssueSidebarSections({
sections,
available,
- revealed = [],
- onRevealEnd,
}: {
sections: Record<IssueSidebarSection, ReactNode>;
available: readonly IssueSidebarSection[];
- /**
- * Hidden sections to show anyway, such as the one a header chip jumped to.
- * Switching one of them in settings ends its reveal, so the switch wins.
- */
- revealed?: readonly IssueSidebarSection[];
- onRevealEnd?: (section: IssueSidebarSection) => void;
}) {
const { t } = useT("issues");
const order = useIssueSidebarSectionsStore(selectIssueSidebarOrder);
const hidden = useIssueSidebarSectionsStore((s) => s.hidden);
const containerRef = useRef<HTMLDivElement>(null);
- const isShown = (id: IssueSidebarSection) => !hidden.includes(id) || revealed.includes(id);
- const visible = order.filter((id) => available.includes(id) && isShown(id));
- const hiddenCount = available.filter((id) => !isShown(id)).length;
- const onShownChange = (id: IssueSidebarSection) => {
- if (revealed.includes(id)) onRevealEnd?.(id);
- };
+ const visible = order.filter((id) => available.includes(id) && !hidden.includes(id));
+ const hiddenCount = available.filter((id) => hidden.includes(id)).length;
const getEmptySections = () =>
new Set(
visible.filter(
@@ -110,7 +98,6 @@ export function IssueSidebarSections({
<IssueSidebarSettings
available={available}
getEmptySections={getEmptySections}
- onShownChange={onShownChange}
trigger={
<IconButton
variant="ghost"
@@ -134,7 +121,6 @@ export function IssueSidebarSections({
<IssueSidebarSettings
available={available}
getEmptySections={getEmptySections}
- onShownChange={onShownChange}
side="top"
align="start"
trigger={
@@ -164,7 +150,6 @@ export function IssueSidebarSettings({
available,
trigger,
getEmptySections,
- onShownChange,
side = "bottom",
align = "end",
}: {
@@ -173,7 +158,6 @@ export function IssueSidebarSettings({
trigger: ReactElement;
/** Shown sections with nothing to render on this issue, read when the popover opens. */
getEmptySections?: () => ReadonlySet<IssueSidebarSection>;
- onShownChange?: (section: IssueSidebarSection, shown: boolean) => void;
side?: "top" | "bottom";
align?: "start" | "end";
}) {
@@ -235,10 +219,7 @@ export function IssueSidebarSettings({
note={note}
shown={shown}
locked={locked}
- onShownChange={(next) => {
- setHidden(id, !next);
- onShownChange?.(id, next);
- }}
+ onShownChange={(next) => setHidden(id, !next)}
/>
);
})}
diff --git a/packages/views/issues/components/issue-wakeup-header-chip.test.tsx b/packages/views/issues/components/issue-wakeup-header-chip.test.tsx
deleted file mode 100644
index d7667be4e7..0000000000
--- a/packages/views/issues/components/issue-wakeup-header-chip.test.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, screen } from "@testing-library/react";
-import type { IssueWakeup, SystemWakeup } from "@multica/core/types";
-import { renderWithI18n } from "../../test/i18n";
-import { IssueWakeupHeaderChip, primaryWakeup } from "./issue-wakeup-header-chip";
-
-let rules: IssueWakeup[] = [];
-let system: SystemWakeup[] = [];
-vi.mock("./wakeup-condition-names", () => ({
- useConditionNames: () => ({ status: (key: string) => key, label: () => undefined, property: () => undefined, actor: (_type: string, id: string) => id }),
-}));
-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));
-vi.mock("@multica/core/issues", () => ({
- issueWakeupsOptions: () => ({ queryKey: ["wakeups"] }),
- issueSystemWakeupsOptions: () => ({ queryKey: ["system"] }),
-}));
-vi.mock("@tanstack/react-query", () => ({
- useQuery: ({ queryKey }: { queryKey: string[] }) => ({ data: queryKey[0] === "wakeups" ? rules : system }),
-}));
-vi.mock("../../common/use-viewing-timezone", () => ({ useViewingTimezone: () => "UTC" }));
-
-const rule = (patch: Partial<IssueWakeup>): IssueWakeup => ({
- id: "w", issue_id: "issue", agent_id: "a", agent_name: "Emacs", instruction: "", kind: "event", mode: "once",
- event_types: ["comment.created"], filter_agent_id: null, filter_task_id: null, interval_seconds: null,
- cron_expression: null, timezone: "UTC", next_fire_at: null, enabled: true, disabled_at: null,
- last_task_id: null, last_error: null, ...patch,
-});
-const childDone: SystemWakeup = {
- id: "rule", revision: 1, default_instruction: "", customized: false, paused_reason: null,
- rule: "child_done", enabled: true, instruction: "", staged: true, stage: 2, total: 2, remaining: 1,
- waiting: [], target: { type: "agent", id: "a", name: "Grok" }, blocked: "", workspace_default: true,
-};
-
-beforeEach(() => {
- rules = [];
- system = [];
-});
-
-describe("primaryWakeup", () => {
- it("prefers a waiting rule, then the soonest schedule, then the system rule", () => {
- const later = rule({ id: "later", kind: "at", next_fire_at: "2030-01-02T00:00:00Z" });
- const sooner = rule({ id: "sooner", kind: "at", next_fire_at: "2030-01-01T00:00:00Z" });
- const reply = rule({ id: "reply" });
- expect(primaryWakeup([later, sooner, reply], [childDone])).toMatchObject({ kind: "rule", rule: { id: "reply" }, count: 4 });
- expect(primaryWakeup([later, sooner], [])).toMatchObject({ rule: { id: "sooner" }, count: 2 });
- expect(primaryWakeup([], [childDone])).toMatchObject({ kind: "system", count: 1 });
- expect(primaryWakeup([], [{ ...childDone, blocked: "backlog" }])).toBeNull();
- });
-
- it("falls back to a paused rule only when nothing else waits", () => {
- const paused = rule({ enabled: false, paused_reason: "loop" });
- expect(primaryWakeup([paused], [])).toMatchObject({ kind: "paused" });
- expect(primaryWakeup([paused, rule({ id: "live" })], [])).toMatchObject({ kind: "rule", rule: { id: "live" } });
- });
-});
-
-describe("IssueWakeupHeaderChip", () => {
- it("says who waits for what, counts the rest and opens the wakeups", () => {
- rules = [rule({ filter_actor_type: "member", filter_actor_id: "u", filter_actor_name: "Jiayuan" }), rule({ id: "w2", kind: "at", next_fire_at: "2030-01-01T00:00:00Z" })];
- system = [childDone];
- const onOpen = vi.fn();
- renderWithI18n(<IssueWakeupHeaderChip issueId="issue" onOpen={onOpen} />, { locale: "zh-Hans" });
- const chip = screen.getByRole("button", { name: /Emacs 在等 Jiayuan 回复 \+2/ });
- expect(chip).toHaveTextContent("Emacs 在等 Jiayuan 回复+2");
- fireEvent.click(chip);
- expect(onOpen).toHaveBeenCalled();
- });
-
- it("names the system rule's target stage", () => {
- system = [childDone];
- renderWithI18n(<IssueWakeupHeaderChip issueId="issue" onOpen={() => {}} />, { locale: "zh-Hans" });
- expect(screen.getByRole("button", { name: /Grok 在等第 2 阶段完成/ })).toBeVisible();
- });
-
- it("renders nothing when the issue waits for nothing", () => {
- const { container } = renderWithI18n(<IssueWakeupHeaderChip issueId="issue" onOpen={() => {}} />);
- expect(container).toBeEmptyDOMElement();
- });
-});
diff --git a/packages/views/issues/components/issue-wakeup-header-chip.tsx b/packages/views/issues/components/issue-wakeup-header-chip.tsx
deleted file mode 100644
index dcbef2f87e..0000000000
--- a/packages/views/issues/components/issue-wakeup-header-chip.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-"use client";
-
-import { memo } from "react";
-import { useQuery } from "@tanstack/react-query";
-import { Bell, TriangleAlert } from "@multica/ui/icons";
-import { issueSystemWakeupsOptions, issueWakeupsOptions } from "@multica/core/issues";
-import type { IssueWakeup, SystemWakeup } from "@multica/core/types";
-import { useWorkspaceId } from "@multica/core/hooks";
-import { cn } from "@multica/ui/lib/utils";
-import { useT } from "../../i18n";
-import { useWakeupText } from "./wakeup-presentation";
-
-/**
- * Picks what the header says an issue is waiting for: the first rule waiting
- * on an event or condition, else the soonest scheduled one, else the
- * sub-issue system rule. A rule the platform paused is shown only when
- * nothing else is waiting, because it needs someone to look at it.
- */
-export function primaryWakeup(rules: readonly IssueWakeup[], system: readonly SystemWakeup[]) {
- const enabled = rules.filter((w) => w.enabled);
- const waiting = enabled.filter((w) => w.kind === "event");
- const scheduled = enabled
- .filter((w) => w.kind !== "event")
- .sort((a, b) => Date.parse(a.next_fire_at ?? "") - Date.parse(b.next_fire_at ?? ""));
- const systemRule = system.find((r) => r.enabled && !r.blocked && r.target);
- const count = enabled.length + (systemRule ? 1 : 0);
- const rule = waiting[0] ?? scheduled[0];
- if (rule) return { kind: "rule" as const, rule, count };
- if (systemRule) return { kind: "system" as const, rule: systemRule, count };
- const paused = rules.find((w) => !w.enabled && w.paused_reason);
- if (paused) return { kind: "paused" as const, rule: paused, count: 1 };
- return null;
-}
-
-/**
- * One line in the issue header saying what the issue is waiting for, e.g.
- * "Emacs is waiting for Jiayuan to reply +2". Opens the Wakeups section.
- */
-export const IssueWakeupHeaderChip = memo(function IssueWakeupHeaderChip({
- issueId,
- onOpen,
-}: {
- issueId: string;
- onOpen: () => void;
-}) {
- const { t } = useT("issues");
- const wsId = useWorkspaceId();
- const text = useWakeupText();
- const { data: rules = [] } = useQuery(issueWakeupsOptions(wsId, issueId));
- const { data: system = [] } = useQuery(issueSystemWakeupsOptions(wsId, issueId));
- const primary = primaryWakeup(rules, system);
- if (!primary) return null;
- const label = String(
- primary.kind === "rule"
- ? text.headline(primary.rule)
- : primary.kind === "system"
- ? t(($) => $.wakeups.wait.header, {
- agent: primary.rule.target?.name ?? "",
- what:
- primary.rule.staged && primary.rule.stage !== null
- ? t(($) => $.wakeups.wait.children_stage, { stage: primary.rule.stage })
- : t(($) => $.wakeups.wait.children_all),
- })
- : t(($) => $.wakeups.wait.paused),
- );
- const Icon = primary.kind === "paused" ? TriangleAlert : Bell;
- return (
- <button
- type="button"
- onClick={onOpen}
- title={label}
- aria-label={`${label}${primary.count > 1 ? ` +${primary.count - 1}` : ""} · ${t(($) => $.wakeups.wait.open)}`}
- className={cn(
- "inline-flex h-7 max-w-72 min-w-0 items-center gap-1.5 rounded-md border border-border px-2.5 text-caption hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring",
- primary.kind === "paused" ? "text-warning" : "text-foreground",
- )}
- >
- <Icon className="size-3.5 shrink-0" aria-hidden="true" />
- <span className="min-w-0 truncate max-sm:hidden">{label}</span>
- {primary.count > 1 && (
- <span className="shrink-0 tabular-nums text-muted-foreground">+{primary.count - 1}</span>
- )}
- </button>
- );
-});
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 812af729a5..6a73895c94 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -854,6 +854,17 @@
"unread_title": "No unread issues",
"clear_button": "Clear filters"
},
+ "presence": {
+ "viewing_one": "{{count}} viewing",
+ "viewing_other": "{{count}} viewing",
+ "editing": "Editing",
+ "watching": "Viewing",
+ "where": "In \"{{section}}\"",
+ "more_one": "{{count}} more: {{names}}",
+ "more_other": "{{count}} more: {{names}}",
+ "name_separator": ", ",
+ "jump_hint": "Click a name to jump to their cursor"
+ },
"agent_live": {
"is_working": "{{name}} is working",
"is_queued": "{{name}} is queued",
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index 533c8212b7..f50c54a3a3 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -837,6 +837,17 @@
"clear_button": "Limpiar filtros",
"unread_title": "No hay tareas sin leer"
},
+ "presence": {
+ "viewing_one": "{{count}} viendo",
+ "viewing_other": "{{count}} viendo",
+ "editing": "Editando",
+ "watching": "Viendo",
+ "where": "En «{{section}}»",
+ "more_one": "{{count}} más: {{names}}",
+ "more_other": "{{count}} más: {{names}}",
+ "name_separator": ", ",
+ "jump_hint": "Haz clic en un nombre para ir a su cursor"
+ },
"agent_live": {
"is_working": "{{name}} está trabajando",
"is_queued": "{{name}} está en cola",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 15f1c63ea7..d9009ce73f 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -854,6 +854,17 @@
"unread_title": "Aucune tâche non lue",
"clear_button": "Effacer les filtres"
},
+ "presence": {
+ "viewing_one": "{{count}} présent",
+ "viewing_other": "{{count}} présents",
+ "editing": "En train de modifier",
+ "watching": "Consultent la page",
+ "where": "Dans « {{section}} »",
+ "more_one": "{{count}} de plus : {{names}}",
+ "more_other": "{{count}} de plus : {{names}}",
+ "name_separator": ", ",
+ "jump_hint": "Cliquez sur un nom pour aller à son curseur"
+ },
"agent_live": {
"is_working": "{{name}} travaille",
"is_queued": "{{name}} est en file d'attente",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 4a3bac0a55..1cb1f140bc 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -820,6 +820,15 @@
"unread_title": "未読のタスクはありません",
"clear_button": "フィルターを解除"
},
+ "presence": {
+ "viewing_other": "{{count}} 人が閲覧中",
+ "editing": "編集中",
+ "watching": "閲覧中",
+ "where": "「{{section}}」を編集中",
+ "more_other": "ほか {{count}} 人:{{names}}",
+ "name_separator": "、",
+ "jump_hint": "名前をクリックすると、その人のカーソルへ移動します"
+ },
"agent_live": {
"is_working": "{{name}} が作業中",
"is_queued": "{{name}} が待機中",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index ba984ae18e..cc487d5ad0 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -820,6 +820,15 @@
"unread_title": "읽지 않은 태스크가 없습니다",
"clear_button": "필터 해제"
},
+ "presence": {
+ "viewing_other": "{{count}}명 보는 중",
+ "editing": "편집 중",
+ "watching": "보는 중",
+ "where": "'{{section}}' 편집 중",
+ "more_other": "외 {{count}}명: {{names}}",
+ "name_separator": ", ",
+ "jump_hint": "이름을 누르면 그 사람의 커서로 이동합니다"
+ },
"agent_live": {
"is_working": "{{name}} 작업 중",
"is_queued": "{{name}} 대기 중",
diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.json
index b3018310a8..39bb85ac18 100644
--- a/packages/views/locales/ru/issues.json
+++ b/packages/views/locales/ru/issues.json
@@ -921,6 +921,21 @@
"clear_button": "Очистить фильтры",
"unread_title": "Нет непрочитанных задач"
},
+ "presence": {
+ "viewing_one": "{{count}} смотрит",
+ "viewing_few": "{{count}} смотрят",
+ "viewing_many": "{{count}} смотрят",
+ "viewing_other": "{{count}} смотрят",
+ "editing": "Редактируют",
+ "watching": "Смотрят",
+ "where": "В «{{section}}»",
+ "more_one": "Ещё {{count}}: {{names}}",
+ "more_few": "Ещё {{count}}: {{names}}",
+ "more_many": "Ещё {{count}}: {{names}}",
+ "more_other": "Ещё {{count}}: {{names}}",
+ "name_separator": ", ",
+ "jump_hint": "Нажмите на имя, чтобы перейти к курсору"
+ },
"agent_live": {
"is_working": "{{name}} работает",
"is_queued": "{{name}} в очереди",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index d0298eac98..c2e48582c7 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -820,6 +820,15 @@
"unread_title": "没有未读任务",
"clear_button": "清除筛选"
},
+ "presence": {
+ "viewing_other": "{{count}} 人在看",
+ "editing": "正在编辑",
+ "watching": "在看",
+ "where": "在改\"{{section}}\"",
+ "more_other": "还有 {{count}} 人:{{names}}",
+ "name_separator": "、",
+ "jump_hint": "点名字跳到对方的光标"
+ },
"agent_live": {
"is_working": "{{name}} 在工作",
"is_queued": "{{name}} 排队中",
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index 68da04f1ae..297abf6be7 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -820,6 +820,15 @@
"unread_title": "沒有未讀任務",
"clear_button": "清除篩選"
},
+ "presence": {
+ "viewing_other": "{{count}} 人在看",
+ "editing": "正在編輯",
+ "watching": "在看",
+ "where": "在改「{{section}}」",
+ "more_other": "還有 {{count}} 人:{{names}}",
+ "name_separator": "、",
+ "jump_hint": "點名字跳到對方的游標"
+ },
"agent_live": {
"is_working": "{{name}} 在工作",
"is_queued": "{{name}} 排隊中",
diff --git a/patches/@[email protected] b/patches/@[email protected]
new file mode 100644
index 0000000000..2058f7b876
--- /dev/null
+++ b/patches/@[email protected]
@@ -0,0 +1,114 @@
+diff --git a/dist/index.cjs b/dist/index.cjs
+index c0c4c65b0e1f3a6b4e44e021ccbd81bce0f9ab7d..a3aad29288f17d848ff708201279edfe77c68f1c 100644
+--- a/dist/index.cjs
++++ b/dist/index.cjs
+@@ -576,7 +576,7 @@ const findAbsolutePositionAfterStructuralChange = (oldDoc, newDoc, absPos) => {
+ //#endregion
+ //#region src/lib/utils/positions/isMisresolvedAfterStructuralChange.ts
+ /** Detects a position that moved into a different block. */
+-const isMisresolvedAfterStructuralChange = (oldDoc, newDoc, oldAbs, resolvedAbs) => {
++const isMisresolvedAfterStructuralChange = (oldDoc, newDoc, oldAbs, resolvedAbs, inLiveBlock = false) => {
+ if (resolvedAbs === null) return false;
+ const $old = oldDoc.resolve(oldAbs);
+ const $new = newDoc.resolve(resolvedAbs);
+@@ -586,6 +586,11 @@ const isMisresolvedAfterStructuralChange = (oldDoc, newDoc, oldAbs, resolvedAbs)
+ if ($old.parentOffset !== 0 && $new.parentOffset === 0) return true;
+ const bothAtStart = $old.parentOffset === 0 && $new.parentOffset === 0;
+ const suspicious = $old.parentOffset !== $new.parentOffset || $old.parent.type !== $new.parent.type || !attrsEqual($old.parent.attrs, $new.parent.attrs);
++ // multica patch: a block with the same text, landed on through a block Yjs still
++ // has, is where the selection is. Matching "the Nth block with this text" instead
++ // moves a caret in a fresh empty paragraph into whichever empty paragraph a
++ // collaborator opened above it.
++ if (bothAtStart && !suspicious && inLiveBlock) return false;
+ if (bothAtStart || suspicious) {
+ const expected = findAbsolutePositionAfterStructuralChange(oldDoc, newDoc, oldAbs);
+ return expected !== null && expected !== resolvedAbs;
+@@ -594,9 +599,18 @@ const isMisresolvedAfterStructuralChange = (oldDoc, newDoc, oldAbs, resolvedAbs)
+ };
+ //#endregion
+ //#region src/lib/utils/positions/restoreRelativeSelection.ts
+-const recoverSelectionEndpoint = (newDoc, oldDoc, oldAbs, resolved) => {
++const isInLiveBlock = (y, documentType, relPos) => {
++ const decoded = yjs.createAbsolutePositionFromRelativePosition(relPos, y);
++ if (decoded === null || decoded.type === documentType) return false;
++ for (let type = decoded.type; type !== documentType;) {
++ if (type === null || type._item === null || type._item.deleted) return false;
++ type = getYParent(type._item);
++ }
++ return true;
++};
++const recoverSelectionEndpoint = (newDoc, oldDoc, oldAbs, resolved, inLiveBlock) => {
+ if (oldAbs == null || oldAbs < 0 || oldAbs > oldDoc.content.size) return resolved;
+- if (!(resolved === null || oldAbs > 1 && resolved <= 1 || isMisresolvedAfterStructuralChange(oldDoc, newDoc, oldAbs, resolved))) return resolved;
++ if (!(resolved === null || oldAbs > 1 && resolved <= 1 || isMisresolvedAfterStructuralChange(oldDoc, newDoc, oldAbs, resolved, inLiveBlock))) return resolved;
+ const recovered = findAbsolutePositionAfterStructuralChange(oldDoc, newDoc, oldAbs);
+ return recovered !== null ? recovered : resolved;
+ };
+@@ -615,8 +629,8 @@ const restoreRelativeSelection = (tr, relSel, binding, oldDoc) => {
+ let anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping);
+ let head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping);
+ if (oldDoc != null) {
+- anchor = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absAnchor, anchor);
+- head = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absHead, head);
++ anchor = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absAnchor, anchor, isInLiveBlock(binding.doc, binding.type, relSel.anchor));
++ head = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absHead, head, isInLiveBlock(binding.doc, binding.type, relSel.head));
+ }
+ if (anchor === null) anchor = head;
+ if (head === null) head = anchor;
+diff --git a/dist/index.js b/dist/index.js
+index 186b363b7d87eb2e935882ca3b72919378df1041..b36ca1c31b3803b09e30dade374943d99b380432 100644
+--- a/dist/index.js
++++ b/dist/index.js
+@@ -543,7 +543,7 @@ const findAbsolutePositionAfterStructuralChange = (oldDoc, newDoc, absPos) => {
+ //#endregion
+ //#region src/lib/utils/positions/isMisresolvedAfterStructuralChange.ts
+ /** Detects a position that moved into a different block. */
+-const isMisresolvedAfterStructuralChange = (oldDoc, newDoc, oldAbs, resolvedAbs) => {
++const isMisresolvedAfterStructuralChange = (oldDoc, newDoc, oldAbs, resolvedAbs, inLiveBlock = false) => {
+ if (resolvedAbs === null) return false;
+ const $old = oldDoc.resolve(oldAbs);
+ const $new = newDoc.resolve(resolvedAbs);
+@@ -553,6 +553,11 @@ const isMisresolvedAfterStructuralChange = (oldDoc, newDoc, oldAbs, resolvedAbs)
+ if ($old.parentOffset !== 0 && $new.parentOffset === 0) return true;
+ const bothAtStart = $old.parentOffset === 0 && $new.parentOffset === 0;
+ const suspicious = $old.parentOffset !== $new.parentOffset || $old.parent.type !== $new.parent.type || !attrsEqual($old.parent.attrs, $new.parent.attrs);
++ // multica patch: a block with the same text, landed on through a block Yjs still
++ // has, is where the selection is. Matching "the Nth block with this text" instead
++ // moves a caret in a fresh empty paragraph into whichever empty paragraph a
++ // collaborator opened above it.
++ if (bothAtStart && !suspicious && inLiveBlock) return false;
+ if (bothAtStart || suspicious) {
+ const expected = findAbsolutePositionAfterStructuralChange(oldDoc, newDoc, oldAbs);
+ return expected !== null && expected !== resolvedAbs;
+@@ -561,9 +566,18 @@ const isMisresolvedAfterStructuralChange = (oldDoc, newDoc, oldAbs, resolvedAbs)
+ };
+ //#endregion
+ //#region src/lib/utils/positions/restoreRelativeSelection.ts
+-const recoverSelectionEndpoint = (newDoc, oldDoc, oldAbs, resolved) => {
++const isInLiveBlock = (y, documentType, relPos) => {
++ const decoded = Y.createAbsolutePositionFromRelativePosition(relPos, y);
++ if (decoded === null || decoded.type === documentType) return false;
++ for (let type = decoded.type; type !== documentType;) {
++ if (type === null || type._item === null || type._item.deleted) return false;
++ type = getYParent(type._item);
++ }
++ return true;
++};
++const recoverSelectionEndpoint = (newDoc, oldDoc, oldAbs, resolved, inLiveBlock) => {
+ if (oldAbs == null || oldAbs < 0 || oldAbs > oldDoc.content.size) return resolved;
+- if (!(resolved === null || oldAbs > 1 && resolved <= 1 || isMisresolvedAfterStructuralChange(oldDoc, newDoc, oldAbs, resolved))) return resolved;
++ if (!(resolved === null || oldAbs > 1 && resolved <= 1 || isMisresolvedAfterStructuralChange(oldDoc, newDoc, oldAbs, resolved, inLiveBlock))) return resolved;
+ const recovered = findAbsolutePositionAfterStructuralChange(oldDoc, newDoc, oldAbs);
+ return recovered !== null ? recovered : resolved;
+ };
+@@ -582,8 +596,8 @@ const restoreRelativeSelection = (tr, relSel, binding, oldDoc) => {
+ let anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping);
+ let head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping);
+ if (oldDoc != null) {
+- anchor = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absAnchor, anchor);
+- head = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absHead, head);
++ anchor = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absAnchor, anchor, isInLiveBlock(binding.doc, binding.type, relSel.anchor));
++ head = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absHead, head, isInLiveBlock(binding.doc, binding.type, relSel.head));
+ }
+ if (anchor === null) anchor = head;
+ if (head === null) head = anchor;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a463c9efe2..6f86b32ab3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -225,6 +225,9 @@ overrides:
builder-util-runtime: 9.7.0
patchedDependencies:
+ '@tiptap/[email protected]':
+ hash: 14d7ede9660b3b5d4a79d087e330a430d8ad458dfcaeca5dacba6e5a9f1d7bdd
+ path: patches/@[email protected]
hash: 52e0bb7a9afc2d62b773afaf938f3be85fde749ce4047635e71547c1ba8cde0e
path: apps/mobile/patches/[email protected]
@@ -1269,10 +1272,10 @@ importers:
'@tiptap/extension-collaboration':
specifier: 3.31.3
+ version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected](patch_hash=14d7ede9660b3b5d4a79d087e330a430d8ad458dfcaeca5dacba6e5a9f1d7bdd)([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])
'@tiptap/extension-collaboration-caret':
specifier: 3.31.3
+ version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected](patch_hash=14d7ede9660b3b5d4a79d087e330a430d8ad458dfcaeca5dacba6e5a9f1d7bdd)([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))
'@tiptap/extension-document':
specifier: 3.31.3
version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))
@@ -1332,7 +1335,7 @@ importers:
version: 3.31.3(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
'@tiptap/y-tiptap':
specifier: ^3.3.1
+ version: 3.3.1(patch_hash=14d7ede9660b3b5d4a79d087e330a430d8ad458dfcaeca5dacba6e5a9f1d7bdd)([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])
cmdk:
specifier: 'catalog:'
@@ -16247,17 +16250,17 @@ snapshots:
dependencies:
'@tiptap/core': 3.31.3(@tiptap/[email protected])
+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected](patch_hash=14d7ede9660b3b5d4a79d087e330a430d8ad458dfcaeca5dacba6e5a9f1d7bdd)([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))':
dependencies:
'@tiptap/core': 3.31.3(@tiptap/[email protected])
'@tiptap/pm': 3.31.3
+ '@tiptap/y-tiptap': 3.3.1(patch_hash=14d7ede9660b3b5d4a79d087e330a430d8ad458dfcaeca5dacba6e5a9f1d7bdd)([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])
+ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected](patch_hash=14d7ede9660b3b5d4a79d087e330a430d8ad458dfcaeca5dacba6e5a9f1d7bdd)([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])':
dependencies:
'@tiptap/core': 3.31.3(@tiptap/[email protected])
'@tiptap/pm': 3.31.3
+ '@tiptap/y-tiptap': 3.3.1(patch_hash=14d7ede9660b3b5d4a79d087e330a430d8ad458dfcaeca5dacba6e5a9f1d7bdd)([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])
yjs: 13.6.33
@@ -16451,7 +16454,7 @@ snapshots:
'@tiptap/core': 3.31.3(@tiptap/[email protected])
'@tiptap/pm': 3.31.3
+ '@tiptap/[email protected](patch_hash=14d7ede9660b3b5d4a79d087e330a430d8ad458dfcaeca5dacba6e5a9f1d7bdd)([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])':
dependencies:
lib0: 0.2.120
prosemirror-model: 1.25.12
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 043d41b4be..033c18873d 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -164,6 +164,8 @@ var concurrentIndexCleanups = map[string]string{
"712_dashboard_range_view_scope_idx": "uq_dashboard_range_view_scope",
"714_doc_collab_state_pkey_index": "doc_collab_state_pkey_idx",
"716_doc_revision_pkey_index": "doc_revision_pkey_idx",
+ "724_issue_description_collab_state_pkey_index": "issue_description_collab_state_pkey_idx",
+ "726_issue_description_revision_pkey_index": "issue_description_revision_pkey_idx",
"671_weixin_account_state_unique_index": "weixin_account_state_pkey",
"669_weixin_login_session_unique_index": "weixin_login_session_pkey",
"666_weixin_login_expiry_idx": "weixin_login_expiry_idx",
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 287841a50f..186e68374b 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -304,6 +304,20 @@ var issueUpdateCmd = &cobra.Command{
RunE: runIssueUpdate,
}
+var issueEditDescriptionCmd = &cobra.Command{
+ Use: "edit-description <id>",
+ Short: "Replace exact text in an issue's description",
+ Long: "Replace text in an issue's description, quoting it exactly as it appears now " +
+ "(with enough surrounding text to be unique), or at least once with --replace-all. " +
+ "The edit lands wherever that text is, even while people are editing the description live; " +
+ "it fails only if someone changed that very text. Prefer this over `issue update --description*` " +
+ "for changing part of a description.",
+ Example: ` multica issue edit-description MUL-123 --old "Status: draft" --new "Status: ready"
+ multica issue edit-description MUL-123 --old-file old.md --new-file new.md`,
+ Args: exactArgs(1),
+ RunE: runIssueEditDescription,
+}
+
var issueAssignCmd = &cobra.Command{
Use: "assign <id>",
Short: "Assign an issue to a member, agent, or squad",
@@ -626,6 +640,7 @@ func init() {
issueCmd.AddCommand(issueChildrenCmd)
issueCmd.AddCommand(issueCreateCmd)
issueCmd.AddCommand(issueUpdateCmd)
+ issueCmd.AddCommand(issueEditDescriptionCmd)
issueCmd.AddCommand(issueAssignCmd)
issueCmd.AddCommand(issueStatusCmd)
issueCmd.AddCommand(issueDeleteCmd)
@@ -712,6 +727,7 @@ func init() {
issueUpdateCmd.Flags().String("description", "", "New description (preserves literal text. Use --description-stdin or --description-file for multi-line input)")
issueUpdateCmd.Flags().Bool("description-stdin", false, "Read new description from stdin (preserves multi-line content verbatim)")
issueUpdateCmd.Flags().String("description-file", "", "Read new description from a UTF-8 file (preserves multi-line content verbatim; use this on Windows when stdin piping mangles non-ASCII bytes). The path must be inside the current working directory unless --allow-external-file is set.")
+ issueUpdateCmd.Flags().Int64("description-base-revision", 0, "The description_revision (from `multica issue get`) your new description was written from. Changes made since then are merged in, and the update is refused only where both changed the same paragraphs. Without it the description is replaced as given.")
issueUpdateCmd.Flags().Bool("allow-external-file", false, "Allow --description-file / --attachment to read a path outside the current working directory. Off by default so a stale temp file from another run/environment can't be picked up (MUL-4252).")
issueUpdateCmd.Flags().StringArray("attachment", nil, "Local file path to attach (one literal path per flag; repeat --attachment for multiple files); references are appended to the end of the description, except where the description already links the same path (e.g. ![shot](./a.png)), which is rewritten to the uploaded file in place")
issueUpdateCmd.Flags().String("status", "", "New status")
@@ -729,6 +745,14 @@ func init() {
issueUpdateCmd.Flags().String("duplicate-of", "", "Mark the issue as a duplicate of this original issue (key like MUL-123, or full UUID) and cancel it; --status, if given, must be cancelled, and description/attachment changes must go in a separate update")
issueUpdateCmd.Flags().String("output", "json", "Output format: table or json")
+ // issue edit-description
+ issueEditDescriptionCmd.Flags().String("old", "", "Exact text to replace (required)")
+ issueEditDescriptionCmd.Flags().String("old-file", "", "Read the text to replace from a UTF-8 file")
+ issueEditDescriptionCmd.Flags().String("new", "", "Replacement text")
+ issueEditDescriptionCmd.Flags().String("new-file", "", "Read the replacement from a UTF-8 file")
+ issueEditDescriptionCmd.Flags().Bool("replace-all", false, "Replace every occurrence of --old")
+ issueEditDescriptionCmd.Flags().String("output", "json", "Output format: table or json")
+
// issue status
issueStatusCmd.Flags().Bool("no-start", false, "Change status without starting an agent run")
issueStatusCmd.Flags().String("duplicate-of", "", "Mark the issue as a duplicate of this original issue (key like MUL-123, or full UUID); the status must be cancelled")
@@ -1998,6 +2022,11 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {
return fmt.Errorf("--duplicate-of cannot be combined with --description, --description-stdin, --description-file or --attachment; mark the duplicate first, then change the description in a separate update")
}
+ if descStdin, _ := cmd.Flags().GetBool("description-stdin"); cmd.Flags().Changed("description-base-revision") &&
+ !cmd.Flags().Changed("description") && !descStdin && !cmd.Flags().Changed("description-file") {
+ return fmt.Errorf("--description-base-revision needs a new description: pass --description, --description-stdin or --description-file")
+ }
+
client, err := newAPIClient(cmd)
if err != nil {
return err
@@ -2031,6 +2060,10 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {
return err
}
body["description"] = desc
+ if cmd.Flags().Changed("description-base-revision") {
+ base, _ := cmd.Flags().GetInt64("description-base-revision")
+ body["description_base_revision"] = base
+ }
}
if statusChanged {
body["status"] = statusFlag
@@ -2151,7 +2184,7 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {
if len(attachmentIDs) > 0 {
return fmt.Errorf("update issue (uploaded IDs: %v): %w", attachmentIDs, err)
}
- return fmt.Errorf("update issue: %w", err)
+ return issueDescriptionWriteError("update issue", err)
}
} else {
// Keep issue update's response shape without issuing an empty update.
@@ -2192,6 +2225,78 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {
return cli.PrintJSON(os.Stdout, result)
}
+// issueDescriptionWriteError explains a refused description write and how to
+// redo it; other errors pass through.
+func issueDescriptionWriteError(action string, err error) error {
+ var httpErr *cli.HTTPError
+ if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusConflict {
+ switch {
+ case strings.Contains(httpErr.Body, "issue_description_merge_conflict"):
+ return fmt.Errorf("%s: someone changed the same paragraphs of the description since your base revision, so nothing was written. "+
+ "The conflicts list both versions; apply your change with `multica issue edit-description`, "+
+ "or run `multica issue get` and retry from the new description_revision (%s)", action, httpErr.Body)
+ case strings.Contains(httpErr.Body, "issue_description_edit_failed"):
+ return fmt.Errorf("%s: nothing was written because --old does not match the description exactly once. "+
+ "Run `multica issue get`, quote the current text (with more context if it repeats), and retry (%s)",
+ action, httpErr.Body)
+ case strings.Contains(httpErr.Body, "issue_description"):
+ return fmt.Errorf("%s: --description-base-revision is too old to merge from, so nothing was written. "+
+ "Run `multica issue get` for the latest description and description_revision, or change part of it with `multica issue edit-description` (%s)",
+ action, httpErr.Body)
+ }
+ }
+ return fmt.Errorf("%s: %w", action, err)
+}
+
+func runIssueEditDescription(cmd *cobra.Command, args []string) error {
+ oldText, hasOld, err := readEditText(cmd, "old")
+ if err != nil {
+ return err
+ }
+ if !hasOld || oldText == "" {
+ return fmt.Errorf("--old (or --old-file) is required: the exact text to replace")
+ }
+ newText, hasNew, err := readEditText(cmd, "new")
+ if err != nil {
+ return err
+ }
+ if !hasNew {
+ return fmt.Errorf("--new (or --new-file) is required; pass --new \"\" to delete the text")
+ }
+ if err := guardLocalPathLinks(newText, "issue description",
+ "Attach the file with `multica issue update <issue-id> --attachment <path>` instead."); err != nil {
+ return err
+ }
+ replaceAll, _ := cmd.Flags().GetBool("replace-all")
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+ issueRef, err := resolveIssueRef(ctx, client, args[0])
+ if err != nil {
+ return fmt.Errorf("resolve issue: %w", err)
+ }
+ body := map[string]any{
+ "edits": []map[string]any{{"old_text": oldText, "new_text": newText, "replace_all": replaceAll}},
+ }
+ var result map[string]any
+ if err := client.PostJSON(ctx, "/api/issues/"+url.PathEscape(issueRef.ID)+"/description/edits", body, &result); err != nil {
+ return issueDescriptionWriteError("edit issue description", err)
+ }
+ output, _ := cmd.Flags().GetString("output")
+ if output == "table" {
+ cli.PrintTable(os.Stdout, []string{"KEY", "TITLE", "DESCRIPTION REVISION"}, [][]string{{
+ issueDisplayKey(result), strVal(result, "title"), strVal(result, "description_revision"),
+ }})
+ return nil
+ }
+ delete(result, "description")
+ return cli.PrintJSON(os.Stdout, result)
+}
+
func runIssueAssign(cmd *cobra.Command, args []string) error {
toName, _ := cmd.Flags().GetString("to")
unassign, _ := cmd.Flags().GetBool("unassign")
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index 5dd7c67b06..1b6c8d4647 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -3863,6 +3863,7 @@ func newIssueUpdateTestCmd() *cobra.Command {
cmd.Flags().String("description", "", "")
cmd.Flags().Bool("description-stdin", false, "")
cmd.Flags().String("description-file", "", "")
+ cmd.Flags().Int64("description-base-revision", 0, "")
cmd.Flags().Bool("allow-external-file", false, "")
cmd.Flags().StringArray("attachment", nil, "")
cmd.Flags().String("status", "", "")
@@ -4059,6 +4060,125 @@ func TestRunIssueUpdateSendsPosition(t *testing.T) {
}
}
+func TestRunIssueUpdateSendsDescriptionBaseRevision(t *testing.T) {
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/MUL-1":
+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "todo"})
+ case r.Method == http.MethodPut && r.URL.Path == "/api/issues/issue-1":
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode body: %v", err)
+ }
+ w.WriteHeader(http.StatusConflict)
+ json.NewEncoder(w).Encode(map[string]any{"code": "issue_description_merge_conflict", "conflicts": []any{}})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueUpdateTestCmd()
+ _ = cmd.Flags().Set("description", "new text")
+ _ = cmd.Flags().Set("description-base-revision", "4")
+ err := runIssueUpdate(cmd, []string{"MUL-1"})
+ if got := body["description_base_revision"]; got != float64(4) {
+ t.Fatalf("description_base_revision = %#v, want 4", got)
+ }
+ if err == nil || !strings.Contains(err.Error(), "issue edit-description") {
+ t.Fatalf("err = %v, want a merge conflict pointing at issue edit-description", err)
+ }
+}
+
+func TestRunIssueUpdateRejectsDescriptionBaseRevisionWithoutDescription(t *testing.T) {
+ cmd := newIssueUpdateTestCmd()
+ _ = cmd.Flags().Set("description-base-revision", "4")
+ _ = cmd.Flags().Set("title", "x")
+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:1")
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+ if err := runIssueUpdate(cmd, []string{"MUL-1"}); err == nil || !strings.Contains(err.Error(), "needs a new description") {
+ t.Fatalf("err = %v, want a refusal before any request", err)
+ }
+}
+
+func newIssueEditDescriptionTestCmd() *cobra.Command {
+ cmd := &cobra.Command{Use: "edit-description"}
+ cmd.Flags().String("old", "", "")
+ cmd.Flags().String("old-file", "", "")
+ cmd.Flags().String("new", "", "")
+ cmd.Flags().String("new-file", "", "")
+ cmd.Flags().Bool("replace-all", false, "")
+ cmd.Flags().String("output", "json", "")
+ return cmd
+}
+
+func TestRunIssueEditDescriptionPostsEdit(t *testing.T) {
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/MUL-1":
+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "todo"})
+ case r.Method == http.MethodPost && r.URL.Path == "/api/issues/issue-1/description/edits":
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode body: %v", err)
+ }
+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "description_revision": 3})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueEditDescriptionTestCmd()
+ _ = cmd.Flags().Set("old", "Status: draft")
+ _ = cmd.Flags().Set("new", "Status: ready")
+ _ = cmd.Flags().Set("replace-all", "true")
+ if err := runIssueEditDescription(cmd, []string{"MUL-1"}); err != nil {
+ t.Fatalf("runIssueEditDescription: %v", err)
+ }
+ edits, _ := body["edits"].([]any)
+ if len(edits) != 1 {
+ t.Fatalf("edits = %#v, want one edit", body["edits"])
+ }
+ edit := edits[0].(map[string]any)
+ if edit["old_text"] != "Status: draft" || edit["new_text"] != "Status: ready" || edit["replace_all"] != true {
+ t.Fatalf("edit = %#v", edit)
+ }
+}
+
+func TestRunIssueEditDescriptionExplainsAMissingQuote(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/MUL-1":
+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "todo"})
+ case r.Method == http.MethodPost:
+ w.WriteHeader(http.StatusConflict)
+ json.NewEncoder(w).Encode(map[string]any{"code": "issue_description_edit_failed", "failure": map[string]any{"reason": "not_found"}})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueEditDescriptionTestCmd()
+ _ = cmd.Flags().Set("old", "gone")
+ _ = cmd.Flags().Set("new", "x")
+ err := runIssueEditDescription(cmd, []string{"MUL-1"})
+ if err == nil || !strings.Contains(err.Error(), "does not match the description exactly once") {
+ t.Fatalf("err = %v", err)
+ }
+}
+
func TestRunIssueUpdateNoStartSendsSuppressRun(t *testing.T) {
var body map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/server/cmd/server/activity_listeners.go b/server/cmd/server/activity_listeners.go
index ec97ab4804..b970d0da6e 100644
--- a/server/cmd/server/activity_listeners.go
+++ b/server/cmd/server/activity_listeners.go
@@ -261,7 +261,9 @@ func registerActivityListeners(bus *events.Bus, queries *db.Queries) {
}
}
- if descriptionChanged {
+ if liveEditors, live := payload["description_live_editors"].([]handler.DocContributor); descriptionChanged && live {
+ recordLiveDescriptionActivities(ctx, bus, queries, e, issue, liveEditors)
+ } else if descriptionChanged {
activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
ID: dbid.NewV7(),
WorkspaceID: parseUUID(issue.WorkspaceID),
@@ -331,6 +333,42 @@ func handleTaskActivity(ctx context.Context, bus *events.Bus, queries *db.Querie
// publishActivityEvent sends an activity:created event for WS broadcasting.
// Payload matches frontend ActivityCreatedPayload: { issue_id, entry: TimelineEntry }
+// recordLiveDescriptionActivities records a live editing session as one
+// description_updated entry per editor rather than one per autosave: an editor
+// who already has a live entry from the last half hour gets no new one.
+func recordLiveDescriptionActivities(ctx context.Context, bus *events.Bus, queries *db.Queries, e events.Event, issue handler.IssueResponse, editors []handler.DocContributor) {
+ for _, editor := range editors {
+ recent, err := queries.HasRecentLiveDescriptionActivity(ctx, db.HasRecentLiveDescriptionActivityParams{
+ IssueID: parseUUID(issue.ID),
+ ActorType: util.StrToText(editor.Type),
+ ActorID: parseUUID(editor.ID),
+ })
+ if err != nil {
+ slog.Error("activity: failed to check live description activity",
+ "issue_id", issue.ID, "error", err)
+ continue
+ }
+ if recent {
+ continue
+ }
+ activity, err := queries.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(),
+ WorkspaceID: parseUUID(issue.WorkspaceID),
+ IssueID: parseUUID(issue.ID),
+ ActorType: util.StrToText(editor.Type),
+ ActorID: parseUUID(editor.ID),
+ Action: "description_updated",
+ Details: []byte(`{"live":"true"}`),
+ })
+ if err != nil {
+ slog.Error("activity: failed to record live description change",
+ "issue_id", issue.ID, "error", err)
+ continue
+ }
+ publishActivityEvent(bus, e, activity)
+ }
+}
+
func publishActivityEvent(bus *events.Bus, original events.Event, activity db.ActivityLog) {
actorType := ""
if activity.ActorType.Valid {
diff --git a/server/cmd/server/issue_description_live_listeners_test.go b/server/cmd/server/issue_description_live_listeners_test.go
new file mode 100644
index 0000000000..bd850d5766
--- /dev/null
+++ b/server/cmd/server/issue_description_live_listeners_test.go
@@ -0,0 +1,125 @@
+package main
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func publishDescriptionChange(bus *events.Bus, issueID, actorID, prev, next string, extra map[string]any) {
+ payload := map[string]any{
+ "issue": handler.IssueResponse{
+ ID: issueID,
+ WorkspaceID: testWorkspaceID,
+ Title: "live description",
+ Status: "todo",
+ Priority: "none",
+ CreatorType: "member",
+ CreatorID: testUserID,
+ Description: &next,
+ },
+ "description_changed": true,
+ "prev_description": &prev,
+ }
+ for k, v := range extra {
+ payload[k] = v
+ }
+ bus.Publish(events.Event{
+ Type: protocol.EventIssueUpdated,
+ WorkspaceID: testWorkspaceID,
+ ActorType: "member",
+ ActorID: actorID,
+ Payload: payload,
+ })
+}
+
+func TestActivityLiveDescriptionSessionIsOneEntryPerEditor(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ registerActivityListeners(bus, queries)
+
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ cleanupActivities(t, issueID)
+ cleanupTestIssue(t, issueID)
+ })
+ bobEmail := "[email protected]"
+ bob := createNotificationMember(t, bobEmail)
+ t.Cleanup(func() { cleanupTestUser(t, bobEmail) })
+
+ me := []handler.DocContributor{{Type: "member", ID: testUserID}}
+ both := []handler.DocContributor{{Type: "member", ID: testUserID}, {Type: "member", ID: bob}}
+ for i, editors := range [][]handler.DocContributor{me, me, both, me} {
+ publishDescriptionChange(bus, issueID, testUserID, "v", "v"+string(rune('a'+i)), map[string]any{
+ "description_live_editors": editors,
+ })
+ }
+ activities := listActivitiesForIssue(t, queries, issueID)
+ if len(activities) != 2 {
+ t.Fatalf("a live session must record one entry per editor, got %d", len(activities))
+ }
+ actors := map[string]bool{}
+ for _, a := range activities {
+ var details map[string]string
+ _ = json.Unmarshal(a.Details, &details)
+ if a.Action != "description_updated" || details["live"] != "true" {
+ t.Fatalf("unexpected activity %+v (%s)", a, a.Details)
+ }
+ actors[util.UUIDToString(a.ActorID)] = true
+ }
+ if len(actors) != 2 {
+ t.Fatalf("entries must credit each editor: %v", actors)
+ }
+
+ // A write outside a live session is recorded as it always was.
+ publishDescriptionChange(bus, issueID, testUserID, "v", "agent", nil)
+ if got := len(listActivitiesForIssue(t, queries, issueID)); got != 3 {
+ t.Fatalf("non-live description change must add an entry, got %d", got)
+ }
+}
+
+func TestNotificationLiveDescriptionMentionNotifiesOnce(t *testing.T) {
+ queries := db.New(testPool)
+ bus := newNotificationBus(t, queries)
+
+ mentionedEmail := "[email protected]"
+ mentioned := createNotificationMember(t, mentionedEmail)
+ t.Cleanup(func() { cleanupTestUser(t, mentionedEmail) })
+
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ cleanupInboxForIssue(t, issueID)
+ cleanupTestIssue(t, issueID)
+ })
+
+ key := "member:" + mentioned
+ withMention := "Hi [@M](mention://member/" + mentioned + ")"
+ live := []handler.DocContributor{{Type: "member", ID: testUserID}}
+ // Typed: the first save carrying the mention notifies.
+ publishDescriptionChange(bus, issueID, testUserID, "Hi", withMention, map[string]any{
+ "description_live_editors": live, "description_seen_mentions": []string{},
+ })
+ // Deleted and typed again in the same session: already seen, so quiet.
+ publishDescriptionChange(bus, issueID, testUserID, withMention, "Hi", map[string]any{
+ "description_live_editors": live, "description_seen_mentions": []string{key},
+ })
+ publishDescriptionChange(bus, issueID, testUserID, "Hi", withMention, map[string]any{
+ "description_live_editors": live, "description_seen_mentions": []string{key},
+ })
+
+ items := inboxItemsForRecipient(t, queries, mentioned)
+ mentions := 0
+ for _, item := range items {
+ if item.Type == "mentioned" {
+ mentions++
+ }
+ }
+ if mentions != 1 {
+ t.Fatalf("a mention typed in one live session must notify once, got %d (%d items)", mentions, len(items))
+ }
+}
diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.go
index b5d2bb7041..d2eaab66d0 100644
--- a/server/cmd/server/listeners.go
+++ b/server/cmd/server/listeners.go
@@ -36,7 +36,8 @@ import (
// inherits the same cost silently. Keeping the list declarative puts the
// internal/external payload boundary in one reviewable place.
var internalOnlyPayloadKeys = map[string][]string{
- protocol.EventIssueUpdated: {"prev_description", "prev_title"},
+ // The live-session keys feed activity folding and mention dedup.
+ protocol.EventIssueUpdated: {"prev_description", "prev_title", "description_live_editors", "description_seen_mentions"},
// task:failed error text is consumed synchronously by channel outbounds.
// It may contain provider/runtime detail that belongs in the originating
// chat transcript, not in the workspace-wide realtime fanout.
diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.go
index a7cd11ee28..7418f47993 100644
--- a/server/cmd/server/notification_listeners.go
+++ b/server/cmd/server/notification_listeners.go
@@ -35,6 +35,26 @@ func parseMentions(content string) []mention {
return result
}
+// previousDescriptionMentions keys the mentions an issue:updated description
+// change does not newly introduce: those of the previous description, plus
+// those a live editing session already stored. A mention typed live is saved
+// by autosave while half written, and an editor may delete and retype it;
+// either way it notifies once per session.
+func previousDescriptionMentions(payload map[string]any) map[string]bool {
+ prev := map[string]bool{}
+ if prevDescription, _ := payload["prev_description"].(*string); prevDescription != nil {
+ for _, m := range parseMentions(*prevDescription) {
+ prev[m.Type+":"+m.ID] = true
+ }
+ }
+ if seen, _ := payload["description_seen_mentions"].([]string); seen != nil {
+ for _, key := range seen {
+ prev[key] = true
+ }
+ }
+ return prev
+}
+
// parentBubbleNotifTypes is the allowlist of inbox notification types that
// bubble up from a sub-issue to subscribers of its parent. Other event types
// only notify subscribers of the sub-issue itself, to keep parent watchers'
@@ -912,7 +932,6 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {
descriptionChanged, _ := payload["description_changed"].(bool)
prevAssigneeType, _ := payload["prev_assignee_type"].(*string)
prevAssigneeID, _ := payload["prev_assignee_id"].(*string)
- prevDescription, _ := payload["prev_description"].(*string)
archiveActions := issueFieldActions(payload)
if assigneeChanged {
@@ -1083,12 +1102,7 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {
if descriptionChanged && issue.Description != nil {
newMentions := parseMentions(*issue.Description)
if len(newMentions) > 0 {
- prevMentioned := map[string]bool{}
- if prevDescription != nil {
- for _, m := range parseMentions(*prevDescription) {
- prevMentioned[m.Type+":"+m.ID] = true
- }
- }
+ prevMentioned := previousDescriptionMentions(payload)
var added []mention
for _, m := range newMentions {
if !prevMentioned[m.Type+":"+m.ID] {
@@ -1096,6 +1110,11 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {
}
}
skip := map[string]bool{e.ActorID: true}
+ if editors, ok := payload["description_live_editors"].([]handler.DocContributor); ok {
+ for _, editor := range editors {
+ skip[editor.ID] = true
+ }
+ }
notifyMentionedMembers(bus, queries, e, added, issue.ID, issue.Title, issue.Status,
issue.Title, "", skip, emptyDetails)
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 79588da940..00e268e1aa 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1629,6 +1629,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/", h.GetCollabDoc)
r.Post("/store", h.StoreCollabDoc)
})
+ r.Route("/internal/collab/issues/{id}", func(r chi.Router) {
+ r.Use(h.RequireCollabSecret)
+ r.Get("/", h.GetCollabIssue)
+ r.Post("/store", h.StoreCollabIssue)
+ })
}
// Capability-authenticated attachment download (MUL-5292). Public by
@@ -2258,6 +2263,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Route("/{id}", func(r chi.Router) {
r.Get("/", h.GetIssue)
r.Put("/", h.UpdateIssue)
+ r.Post("/description/edits", h.EditIssueDescription)
+ r.Post("/collab-ticket", h.CreateIssueCollabTicket)
r.Post("/move", h.MoveIssue)
r.Delete("/", h.DeleteIssue)
r.Post("/comments/trigger-preview", h.PreviewCommentTriggers)
diff --git a/server/cmd/server/subscriber_listeners.go b/server/cmd/server/subscriber_listeners.go
index a1d2bfedc2..44453f0836 100644
--- a/server/cmd/server/subscriber_listeners.go
+++ b/server/cmd/server/subscriber_listeners.go
@@ -89,12 +89,7 @@ func registerSubscriberListeners(bus *events.Bus, pool *pgxpool.Pool) {
if descriptionChanged, _ := payload["description_changed"].(bool); descriptionChanged && issue.Description != nil {
newMentions := parseMentions(*issue.Description)
if len(newMentions) > 0 {
- prevMentioned := map[string]bool{}
- if prevDescription, _ := payload["prev_description"].(*string); prevDescription != nil {
- for _, m := range parseMentions(*prevDescription) {
- prevMentioned[m.Type+":"+m.ID] = true
- }
- }
+ prevMentioned := previousDescriptionMentions(payload)
for _, m := range newMentions {
if !prevMentioned[m.Type+":"+m.ID] {
addSubscriber(bus, queries, e.WorkspaceID, issue.ID, m.Type, m.ID, "mentioned")
diff --git a/server/internal/collab/client.go b/server/internal/collab/client.go
index 046d762bbf..c3959e43a9 100644
--- a/server/internal/collab/client.go
+++ b/server/internal/collab/client.go
@@ -96,27 +96,29 @@ type Result struct {
Failure *EditFailure `json:"failure,omitempty"`
}
-func (c *Client) Write(ctx context.Context, docID string, req WriteRequest) (Result, error) {
- return c.call(ctx, docID, "write", req)
+// Write, Edit and Flush address a live document by its service name:
+// DocumentName for a doc, IssueDocumentName for an issue description.
+func (c *Client) Write(ctx context.Context, document string, req WriteRequest) (Result, error) {
+ return c.call(ctx, document, "write", req)
}
-func (c *Client) Edit(ctx context.Context, docID string, req EditRequest) (Result, error) {
- return c.call(ctx, docID, "edit", req)
+func (c *Client) Edit(ctx context.Context, document string, req EditRequest) (Result, error) {
+ return c.call(ctx, document, "edit", req)
}
-// Flush persists pending editor changes of a loaded doc, so a read sees what
-// people have typed. Docs nobody has open return immediately.
-func (c *Client) Flush(ctx context.Context, docID string) error {
- _, err := c.call(ctx, docID, "flush", struct{}{})
+// Flush persists pending editor changes of a loaded document, so a read sees
+// what people have typed. Documents nobody has open return immediately.
+func (c *Client) Flush(ctx context.Context, document string) error {
+ _, err := c.call(ctx, document, "flush", struct{}{})
return err
}
-func (c *Client) call(ctx context.Context, docID, op string, body any) (Result, error) {
+func (c *Client) call(ctx context.Context, document, op string, body any) (Result, error) {
raw, err := json.Marshal(body)
if err != nil {
return Result{}, err
}
- endpoint := c.baseURL.JoinPath("internal", "documents", DocumentName(docID), op)
+ endpoint := c.baseURL.JoinPath("internal", "documents", document, op)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.String(), bytes.NewReader(raw))
if err != nil {
return Result{}, err
diff --git a/server/internal/collab/collab_test.go b/server/internal/collab/collab_test.go
index 42550796a9..24ec2b1a13 100644
--- a/server/internal/collab/collab_test.go
+++ b/server/internal/collab/collab_test.go
@@ -82,7 +82,7 @@ func TestClientMapsServiceResponses(t *testing.T) {
ctx := context.Background()
content := "new"
- result, err := client.Write(ctx, "abc", WriteRequest{Actor: Actor{Type: "agent", ID: "a"}, Content: &content})
+ result, err := client.Write(ctx, DocumentName("abc"), WriteRequest{Actor: Actor{Type: "agent", ID: "a"}, Content: &content})
if err != nil || result.Status != StatusOK || result.Revision != 7 || !result.Merged {
t.Fatalf("write = %+v, %v", result, err)
}
@@ -91,34 +91,34 @@ func TestClientMapsServiceResponses(t *testing.T) {
}
status, body = http.StatusConflict, `{"error":"edit_failed","status":"edit_failed","revision":3,"content":"c","failure":{"reason":"ambiguous","index":0,"matches":2}}`
- result, err = client.Edit(ctx, "abc", EditRequest{Edits: []TextEdit{{OldText: "x", NewText: "y"}}})
+ result, err = client.Edit(ctx, DocumentName("abc"), EditRequest{Edits: []TextEdit{{OldText: "x", NewText: "y"}}})
if err != nil || result.Status != StatusEditFailed || result.Failure == nil || result.Failure.Matches != 2 {
t.Fatalf("edit = %+v, %v", result, err)
}
status, body = http.StatusNotFound, `{}`
- if result, err = client.Write(ctx, "abc", WriteRequest{}); err != nil || result.Status != StatusGone {
+ if result, err = client.Write(ctx, DocumentName("abc"), WriteRequest{}); err != nil || result.Status != StatusGone {
t.Fatalf("gone = %+v, %v", result, err)
}
status, body = http.StatusRequestEntityTooLarge, `{"error":"content_too_large","status":"too_large","revision":3}`
- if result, err = client.Edit(ctx, "abc", EditRequest{}); err != nil || result.Status != StatusTooLarge {
+ if result, err = client.Edit(ctx, DocumentName("abc"), EditRequest{}); err != nil || result.Status != StatusTooLarge {
t.Fatalf("too large = %+v, %v", result, err)
}
// A refused request must not be written around the running service.
status, body = http.StatusBadRequest, `{"error":"bad"}`
- if _, err = client.Write(ctx, "abc", WriteRequest{}); err == nil || errors.Is(err, ErrUnavailable) {
+ if _, err = client.Write(ctx, DocumentName("abc"), WriteRequest{}); err == nil || errors.Is(err, ErrUnavailable) {
t.Fatalf("400 err = %v, want an error other than ErrUnavailable", err)
}
status, body = http.StatusInternalServerError, `{"error":"boom"}`
- if _, err = client.Write(ctx, "abc", WriteRequest{}); !errors.Is(err, ErrUnavailable) {
+ if _, err = client.Write(ctx, DocumentName("abc"), WriteRequest{}); !errors.Is(err, ErrUnavailable) {
t.Fatalf("500 err = %v, want ErrUnavailable", err)
}
srv.Close()
- if err = client.Flush(ctx, "abc"); !errors.Is(err, ErrUnavailable) {
+ if err = client.Flush(ctx, DocumentName("abc")); !errors.Is(err, ErrUnavailable) {
t.Fatalf("unreachable err = %v, want ErrUnavailable", err)
}
}
diff --git a/server/internal/collab/ticket.go b/server/internal/collab/ticket.go
index cda5465c05..21ca208f88 100644
--- a/server/internal/collab/ticket.go
+++ b/server/internal/collab/ticket.go
@@ -55,3 +55,9 @@ func SignTicket(secret string, t Ticket) string {
func DocumentName(docID string) string {
return "doc:" + docID
}
+
+// IssueDocumentName is the collaboration service's name for an issue's
+// description.
+func IssueDocumentName(issueID string) string {
+ return "issue:" + issueID
+}
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 0ffc45a19e..05ace49ba5 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -288,6 +288,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("- `multica issue comment list <issue-id> [--roots-only] [--summary] [--thread <comment-id> [--tail N] | --recent N] [--since <RFC3339>] [--compact] --output json` — thread-aware comment reads. Read in two bounded steps: scan with `--roots-only --summary`, then expand one thread with `--thread <id> --tail N`. Careful with `--recent N`: it caps THREADS, not comments, and can return the whole history on a small issue. Resolved-thread folding, paging cursors, and full flag semantics: `--help`.\n")
b.WriteString("- `multica issue create --title \"...\" [--description-file <path>] [--priority X] [--status X] [--assignee X | --assignee-id <uuid>] [--parent <issue-id>] [--stage N] [--project <project-id>] [--due-date <YYYY-MM-DD>] [--attachment <path>]` — create an issue. Put agent-authored long descriptions in `--description-file <path>` (heredoc stdin can swallow trailing flags, #4182); write that file inside your working directory, never `/tmp` or shared paths.\n")
b.WriteString("- `multica issue update <id> [--title X] [--description-file <path>] [--priority X] [--status X] [--assignee X] [--parent <issue-id>] [--stage N] [--project <project-id>] [--due-date <YYYY-MM-DD>]` — update fields; pass `--parent \"\"` to clear parent.\n")
+ b.WriteString("- `multica issue edit-description <id> --old <exact text> --new <text>` — people may be editing a description live, so change part of it with this; a whole new `--description-file` on `issue update` should carry `--description-base-revision <description_revision from issue get>` so edits made since are merged in.\n")
b.WriteString("- `multica issue assign <id> (--to X | --to-id <uuid> | --unassign)` — change ownership; assigning to an agent can start a run.\n")
writeIssueStatusCommand(b, ctx)
b.WriteString(duplicateOfCommandLine)
diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.go
index 9acd80b011..10eacc2e1c 100644
--- a/server/internal/featureflags/keys.go
+++ b/server/internal/featureflags/keys.go
@@ -42,6 +42,13 @@ const (
// for a deployment. It is a GLOBAL switch. Turning it off leaves existing
// doc rows untouched — they simply become unreachable until it is back on.
DocsV1 = "docs_v1"
+ // IssueDescriptionLive lets people and agents edit an issue's description
+ // together in real time (MUL-9778), on the collaboration service Docs use.
+ // Off by default; FF_ISSUE_DESCRIPTION_LIVE=true turns it on where that
+ // service is configured. It is a GLOBAL switch. Turning it off sends
+ // editors back to saving through the API; sessions already open still
+ // save what was typed.
+ IssueDescriptionLive = "issue_description_live"
// DashboardHistory365d offers the 365-day range on the workspace dashboard
// (MUL-9490). On by default; FF_DASHBOARD_HISTORY_365D=off hides the range
// again if the year-long dashboard queries turn out too slow for a
@@ -101,6 +108,10 @@ func DocsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {
return flags.IsEnabled(ctx, DocsV1, false)
}
+func IssueDescriptionLiveEnabled(ctx context.Context, flags *featureflag.Service) bool {
+ return flags.IsEnabled(ctx, IssueDescriptionLive, false)
+}
+
func DashboardHistory365dEnabled(ctx context.Context, flags *featureflag.Service) bool {
return flags.IsEnabled(ctx, DashboardHistory365d, true)
}
diff --git a/server/internal/handler/doc_collab.go b/server/internal/handler/doc_collab.go
index 616e91e784..9bfb5bc440 100644
--- a/server/internal/handler/doc_collab.go
+++ b/server/internal/handler/doc_collab.go
@@ -156,7 +156,7 @@ func (h *Handler) flushDocCollab(ctx context.Context, docID pgtype.UUID) {
}
ctx, cancel := context.WithTimeout(ctx, docCollabFlushTimeout)
defer cancel()
- if err := h.Collab.Flush(ctx, uuidToString(docID)); err != nil {
+ if err := h.Collab.Flush(ctx, collab.DocumentName(uuidToString(docID))); err != nil {
slog.Warn("doc collab flush failed", "doc_id", uuidToString(docID), "error", err)
}
}
@@ -330,7 +330,7 @@ func (h *Handler) updateDocViaCollab(w http.ResponseWriter, r *http.Request, wsU
write.Title = req.Title
}
- result, err := h.Collab.Write(ctx, uuidToString(doc.ID), write)
+ result, err := h.Collab.Write(ctx, collab.DocumentName(uuidToString(doc.ID)), write)
if err != nil {
if errors.Is(err, collab.ErrUnavailable) {
slog.Warn("doc collab write failed; writing directly", "doc_id", uuidToString(doc.ID), "error", err)
@@ -428,7 +428,7 @@ func (h *Handler) EditDoc(w http.ResponseWriter, r *http.Request) {
if taskID.Valid {
edit.TaskID = uuidToString(taskID)
}
- result, err := h.Collab.Edit(ctx, uuidToString(docUUID), edit)
+ result, err := h.Collab.Edit(ctx, collab.DocumentName(uuidToString(docUUID)), edit)
if err == nil {
h.writeCollabResult(w, r, wsUUID, docUUID, result)
return
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index f0f24836cb..c6046701d2 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -87,6 +87,10 @@ type IssueResponse struct {
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Revision int64 `json:"revision"`
+ // DescriptionRevision counts changes to the description alone. A whole
+ // rewrite sends it back as description_base_revision so it is merged
+ // with what others changed since. Omitted by list endpoints.
+ DescriptionRevision *int64 `json:"description_revision,omitempty"`
// LastActivityAt is the latest semantic issue activity. It stays nullable
// while the operator-run historical backfill is incomplete.
LastActivityAt *string `json:"last_activity_at"`
@@ -486,33 +490,34 @@ func issueToResponse(i db.Issue, issuePrefix string) IssueResponse {
statusCategory = i.Status
}
return IssueResponse{
- ID: uuidToString(i.ID),
- WorkspaceID: uuidToString(i.WorkspaceID),
- Number: i.Number,
- Identifier: identifier,
- Title: i.Title,
- Description: textToPtr(i.Description),
- Status: i.Status,
- StatusCategory: statusCategory,
- Priority: i.Priority,
- AssigneeType: textToPtr(i.AssigneeType),
- AssigneeID: uuidToPtr(i.AssigneeID),
- CreatorType: i.CreatorType,
- CreatorID: uuidToString(i.CreatorID),
- RequesterID: uuidToPtr(i.RequesterUserID),
- ParentIssueID: uuidToPtr(i.ParentIssueID),
- duplicateOfIssueID: duplicateOfPointer(i.Status, i.DuplicateOfIssueID),
- ProjectID: uuidToPtr(i.ProjectID),
- Position: i.Position,
- Stage: int4ToPtr(i.Stage),
- StartDate: dateToPtr(i.StartDate),
- DueDate: dateToPtr(i.DueDate),
- CreatedAt: timestampToString(i.CreatedAt),
- UpdatedAt: timestampToString(i.UpdatedAt),
- Revision: i.Revision,
- LastActivityAt: timestampToNanoPtr(i.LastActivityAt),
- Metadata: parseIssueMetadata(i.Metadata),
- Properties: parseIssueProperties(i.Properties),
+ ID: uuidToString(i.ID),
+ WorkspaceID: uuidToString(i.WorkspaceID),
+ Number: i.Number,
+ Identifier: identifier,
+ Title: i.Title,
+ Description: textToPtr(i.Description),
+ Status: i.Status,
+ StatusCategory: statusCategory,
+ Priority: i.Priority,
+ AssigneeType: textToPtr(i.AssigneeType),
+ AssigneeID: uuidToPtr(i.AssigneeID),
+ CreatorType: i.CreatorType,
+ CreatorID: uuidToString(i.CreatorID),
+ RequesterID: uuidToPtr(i.RequesterUserID),
+ ParentIssueID: uuidToPtr(i.ParentIssueID),
+ duplicateOfIssueID: duplicateOfPointer(i.Status, i.DuplicateOfIssueID),
+ ProjectID: uuidToPtr(i.ProjectID),
+ Position: i.Position,
+ Stage: int4ToPtr(i.Stage),
+ StartDate: dateToPtr(i.StartDate),
+ DueDate: dateToPtr(i.DueDate),
+ CreatedAt: timestampToString(i.CreatedAt),
+ UpdatedAt: timestampToString(i.UpdatedAt),
+ Revision: i.Revision,
+ DescriptionRevision: &i.DescriptionRevision,
+ LastActivityAt: timestampToNanoPtr(i.LastActivityAt),
+ Metadata: parseIssueMetadata(i.Metadata),
+ Properties: parseIssueProperties(i.Properties),
}
}
@@ -2518,6 +2523,9 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // Agents quote the description back in edits; give them what people
+ // have typed, not the last autosave.
+ issue = h.flushIssueDescriptionCollab(r, issue)
hidden, ok := h.requestHiddenProjects(w, r, uuidToString(issue.WorkspaceID))
if !ok {
return
@@ -3708,17 +3716,22 @@ type UpdateIssueRequest struct {
// that landed asynchronously after that base without making media already
// present in the base impossible for the user to delete. Older clients omit
// it and receive conservative channel-media preservation.
- DescriptionBase *string `json:"description_base,omitempty"`
- Status *string `json:"status"`
- Priority *string `json:"priority"`
- AssigneeType *string `json:"assignee_type"`
- AssigneeID *string `json:"assignee_id"`
- Position *float64 `json:"position"`
- StartDate *string `json:"start_date"`
- DueDate *string `json:"due_date"`
- ParentIssueID *string `json:"parent_issue_id"`
- ProjectID *string `json:"project_id"`
- Stage *int32 `json:"stage"`
+ DescriptionBase *string `json:"description_base,omitempty"`
+ // DescriptionBaseRevision is the description_revision the writer read
+ // before producing Description. With live editing the write is merged
+ // with what changed since, block by block; without it a stale revision
+ // is refused instead of overwriting newer text.
+ DescriptionBaseRevision *int64 `json:"description_base_revision,omitempty"`
+ Status *string `json:"status"`
+ Priority *string `json:"priority"`
+ AssigneeType *string `json:"assignee_type"`
+ AssigneeID *string `json:"assignee_id"`
+ Position *float64 `json:"position"`
+ StartDate *string `json:"start_date"`
+ DueDate *string `json:"due_date"`
+ ParentIssueID *string `json:"parent_issue_id"`
+ ProjectID *string `json:"project_id"`
+ Stage *int32 `json:"stage"`
// AttachmentIDs lets the description editor bind newly uploaded files to
// this issue so they surface in `GET /api/issues/:id/attachments` and the
// editor's preview Eye keeps working past a refresh. Existing bindings
@@ -3833,7 +3846,12 @@ func refreshUntouchedNullableIssueParams(params *db.UpdateIssueParams, current d
var errIssueFieldConflict = errors.New("issue text field conflict")
-func (h *Handler) updateIssueAtomically(ctx context.Context, workspaceID pgtype.UUID, params db.UpdateIssueParams, rawFields map[string]json.RawMessage, titleBase, descriptionBase *string, attachmentIDs []pgtype.UUID, statusKey string, workflowAssignee bool) (db.Issue, db.Issue, bool, error) {
+// errIssueDescriptionRevisionConflict: a description written from a
+// description_base_revision that is no longer current, without the live
+// session that could merge it.
+var errIssueDescriptionRevisionConflict = errors.New("issue description revision conflict")
+
+func (h *Handler) updateIssueAtomically(ctx context.Context, workspaceID pgtype.UUID, params db.UpdateIssueParams, rawFields map[string]json.RawMessage, titleBase, descriptionBase *string, descriptionBaseRevision *int64, attachmentIDs []pgtype.UUID, statusKey string, workflowAssignee bool) (db.Issue, db.Issue, bool, error) {
if h.TxStarter == nil {
return db.Issue{}, db.Issue{}, false, errors.New("atomic issue update requires transaction starter")
}
@@ -3870,6 +3888,10 @@ func (h *Handler) updateIssueAtomically(ctx context.Context, workspaceID pgtype.
return db.Issue{}, current, false, errIssueFieldConflict
}
+ if params.Description.Valid && descriptionBaseRevision != nil && current.DescriptionRevision != *descriptionBaseRevision {
+ return db.Issue{}, current, false, errIssueDescriptionRevisionConflict
+ }
+
if params.Description.Valid {
attachments, listErr := qtx.ListAttachmentsByIssue(ctx, db.ListAttachmentsByIssueParams{
IssueID: current.ID,
@@ -3909,6 +3931,11 @@ func (h *Handler) updateIssueAtomically(ctx context.Context, workspaceID pgtype.
if err != nil {
return db.Issue{}, current, false, fmt.Errorf("update locked issue: %w", err)
}
+ if issue.DescriptionRevision != current.DescriptionRevision {
+ if err := recordIssueDescriptionRevision(ctx, qtx, current, issue); err != nil {
+ return db.Issue{}, current, false, fmt.Errorf("record issue description revision: %w", err)
+ }
+ }
attachmentsChanged := false
if len(attachmentIDs) > 0 {
@@ -4227,6 +4254,32 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
return
}
+ // With live editing on, the description goes through its live session,
+ // merged into what people are typing; the other fields follow as usual.
+ // Everything above has been validated, so nothing is refused after it.
+ // A write pinned to expected_revision stays a direct compare-and-swap of
+ // the whole issue; the live session folds it in on its next save.
+ if client := h.issueCollab(r.Context()); req.Description != nil && req.ExpectedRevision == nil && client != nil {
+ writerType, writerID := h.resolveActor(r, userID, workspaceID)
+ handled, ok := h.updateIssueDescriptionViaCollab(w, r, client, prevIssue, req, writerType, writerID)
+ if !ok {
+ return
+ }
+ if handled {
+ if issueUpdateOnlyDescription(rawFields) {
+ updated, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: prevIssue.ID, WorkspaceID: prevIssue.WorkspaceID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load issue")
+ return
+ }
+ h.writeIssueForCaller(w, r, updated)
+ return
+ }
+ req.Description, req.DescriptionBase, req.DescriptionBaseRevision = nil, nil, nil
+ params.Description = pgtype.Text{}
+ }
+ }
+
// The agent this write hands the issue to gets the change as its own run,
// not also through its event wakeups.
writeCtx := withWakeupHandedTo(r.Context(), h.handedToAgent(r.Context(), prevIssue, params, handoff != nil))
@@ -4235,7 +4288,7 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
if req.Description != nil || req.TitleBase != nil || req.DescriptionBase != nil || len(attachmentIDs) > 0 {
var lockedPrev db.Issue
issue, lockedPrev, attachmentsChanged, err = h.updateIssueAtomically(
- writeCtx, prevIssue.WorkspaceID, params, rawFields, req.TitleBase, req.DescriptionBase, attachmentIDs, statusKeyForGuard, handoff != nil,
+ writeCtx, prevIssue.WorkspaceID, params, rawFields, req.TitleBase, req.DescriptionBase, req.DescriptionBaseRevision, attachmentIDs, statusKeyForGuard, handoff != nil,
)
if lockedPrev.ID.Valid {
prevIssue = lockedPrev
@@ -4254,6 +4307,10 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
writeEditConflict(w, "issue", prevIssue.ID)
return
}
+ if errors.Is(err, errIssueDescriptionRevisionConflict) {
+ writeRevisionConflict(w, "issue_description", prevIssue.ID, *req.DescriptionBaseRevision, prevIssue.DescriptionRevision)
+ return
+ }
if errors.Is(err, pgx.ErrNoRows) && req.ExpectedRevision != nil {
current, reloadErr := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: prevIssue.ID, WorkspaceID: prevIssue.WorkspaceID})
if reloadErr == nil {
@@ -5122,7 +5179,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
// legacy single-update clients that omit description_base.
var lockedPrev db.Issue
issue, lockedPrev, _, err = h.updateIssueAtomically(
- writeCtx, prevIssue.WorkspaceID, params, rawUpdates, nil, nil, nil, issueStatusGuard, handoff != nil,
+ writeCtx, prevIssue.WorkspaceID, params, rawUpdates, nil, nil, nil, nil, issueStatusGuard, handoff != nil,
)
if err == nil {
prevIssue = lockedPrev
diff --git a/server/internal/handler/issue_description_collab.go b/server/internal/handler/issue_description_collab.go
new file mode 100644
index 0000000000..7753e0e897
--- /dev/null
+++ b/server/internal/handler/issue_description_collab.go
@@ -0,0 +1,653 @@
+package handler
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "regexp"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/collab"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/logger"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Live co-editing of issue descriptions (MUL-9778) runs on the same
+// collaboration service as docs (doc_collab.go), under the document name
+// "issue:<id>". The description stays an ordinary issue field: every live
+// save goes through UpdateIssue, so activity, mention notifications and
+// subscriptions follow it as they follow any other description change.
+
+const (
+ // Live saves come every 5 to 30 seconds while someone types. A writer
+ // whose base is more than this many description revisions old gets a
+ // revision conflict instead of a merge.
+ issueDescriptionRevisionsKept = 50
+ issueDescriptionMaxBytes = 2 << 20
+ issueDescriptionSeenMentionsMax = 1000
+)
+
+// issueCollab is the collaboration service for issue descriptions: nil
+// unless it is configured and the issue_description_live flag is on. The
+// internal endpoints it calls back are not gated, so sessions open when the
+// flag goes off still save.
+func (h *Handler) issueCollab(ctx context.Context) *collab.Client {
+ if h.Collab == nil || !featureflags.IssueDescriptionLiveEnabled(ctx, h.FeatureFlags) {
+ return nil
+ }
+ return h.Collab
+}
+
+// recordIssueDescriptionRevision keeps the description of recent revisions,
+// the merge base for a write that started from one of them. The revision
+// being replaced is recorded too: an issue's first description, and one
+// written by a path that keeps no history, has no row of its own.
+func recordIssueDescriptionRevision(ctx context.Context, qtx *db.Queries, prev, issue db.Issue) error {
+ for _, rev := range []db.Issue{prev, issue} {
+ if err := qtx.InsertIssueDescriptionRevision(ctx, db.InsertIssueDescriptionRevisionParams{
+ IssueID: rev.ID, WorkspaceID: rev.WorkspaceID, Revision: rev.DescriptionRevision, Content: rev.Description.String,
+ }); err != nil {
+ return err
+ }
+ }
+ return qtx.PruneIssueDescriptionRevisions(ctx, db.PruneIssueDescriptionRevisionsParams{
+ IssueID: issue.ID, KeepFrom: issue.DescriptionRevision - issueDescriptionRevisionsKept,
+ })
+}
+
+// descriptionOnlyParams writes `description` and leaves every other field as
+// `current` has it.
+func descriptionOnlyParams(current db.Issue, description string, sourceTask pgtype.UUID) db.UpdateIssueParams {
+ return db.UpdateIssueParams{
+ ID: current.ID,
+ SourceTaskID: sourceTask,
+ Description: pgtype.Text{String: description, Valid: true},
+ AssigneeType: current.AssigneeType,
+ AssigneeID: current.AssigneeID,
+ StartDate: current.StartDate,
+ DueDate: current.DueDate,
+ ParentIssueID: current.ParentIssueID,
+ ProjectID: current.ProjectID,
+ Stage: current.Stage,
+ }
+}
+
+// publishIssueDescriptionUpdated announces a write that changed only the
+// description, with the payload UpdateIssue gives the same change. `extra`
+// carries what a live save adds for the listeners.
+func (h *Handler) publishIssueDescriptionUpdated(ctx context.Context, prev, issue db.Issue, actorType, actorID string, extra map[string]any) {
+ resp := issueToResponse(issue, h.getIssuePrefix(ctx, issue.WorkspaceID))
+ h.fillStatusCategory(ctx, issue.WorkspaceID, projectaccess.Hidden{}, &resp)
+ payload := map[string]any{
+ "issue": resp,
+ "assignee_changed": false,
+ "status_changed": false,
+ "priority_changed": false,
+ "project_changed": false,
+ "start_date_changed": false,
+ "due_date_changed": false,
+ "description_changed": true,
+ "title_changed": false,
+ "parent_changed": false,
+ "prev_parent_issue_id": uuidToPtr(prev.ParentIssueID),
+ "prev_title": prev.Title,
+ "prev_assignee_type": textToPtr(prev.AssigneeType),
+ "prev_assignee_id": uuidToPtr(prev.AssigneeID),
+ "prev_status": prev.Status,
+ "prev_priority": prev.Priority,
+ "prev_start_date": dateToPtr(prev.StartDate),
+ "prev_due_date": dateToPtr(prev.DueDate),
+ "prev_description": textToPtr(prev.Description),
+ "creator_type": prev.CreatorType,
+ "creator_id": uuidToString(prev.CreatorID),
+ "duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),
+ "prev_duplicate_of_issue_id": liveDuplicateMark(prev.Status, prev.DuplicateOfIssueID),
+ }
+ for k, v := range extra {
+ payload[k] = v
+ }
+ h.publish(protocol.EventIssueUpdated, uuidToString(issue.WorkspaceID), actorType, actorID, payload)
+}
+
+// writeIssueForCaller answers with the issue as the caller may see it.
+func (h *Handler) writeIssueForCaller(w http.ResponseWriter, r *http.Request, issue db.Issue) {
+ resp := issueToResponse(issue, h.getIssuePrefix(r.Context(), issue.WorkspaceID))
+ hidden, err := h.hiddenProjects(r, uuidToString(issue.WorkspaceID))
+ if err != nil {
+ hidden = projectaccess.Hidden{}
+ }
+ h.fillStatusCategory(r.Context(), issue.WorkspaceID, hidden, &resp)
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// flushIssueDescriptionCollab persists what people have typed into an open
+// description, so an agent reading the issue sees it. Best effort, and only
+// for agents: people read the description from the live session itself, and
+// a slow service must not hold up every issue page.
+func (h *Handler) flushIssueDescriptionCollab(r *http.Request, issue db.Issue) db.Issue {
+ client := h.issueCollab(r.Context())
+ if client == nil {
+ return issue
+ }
+ if actorType, _ := h.resolveActor(r, requestUserID(r), uuidToString(issue.WorkspaceID)); actorType != "agent" {
+ return issue
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), docCollabFlushTimeout)
+ defer cancel()
+ if err := client.Flush(ctx, collab.IssueDocumentName(uuidToString(issue.ID))); err != nil {
+ slog.Warn("issue description collab flush failed", "issue_id", uuidToString(issue.ID), "error", err)
+ return issue
+ }
+ fresh, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: issue.ID, WorkspaceID: issue.WorkspaceID})
+ if err != nil {
+ return issue
+ }
+ return fresh
+}
+
+// CreateIssueCollabTicket lets an editor join the live session of an issue's
+// description. Guests are refused by the guest route list before this runs;
+// the issue loader applies project visibility.
+func (h *Handler) CreateIssueCollabTicket(w http.ResponseWriter, r *http.Request) {
+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ client := h.issueCollab(r.Context())
+ if client == nil {
+ writeJSON(w, http.StatusOK, DocCollabTicketResponse{Enabled: false})
+ return
+ }
+ var req DocCollabTicketRequest
+ if r.Body != nil {
+ _ = json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<10)).Decode(&req)
+ }
+ workspaceID := uuidToString(issue.WorkspaceID)
+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)
+ expires := time.Now().Add(docCollabTicketTTL)
+ document := collab.IssueDocumentName(uuidToString(issue.ID))
+ token := collab.SignTicket(client.Secret(), collab.Ticket{
+ Document: document,
+ WorkspaceID: workspaceID,
+ Actor: h.collabActor(r.Context(), actorType, actorID),
+ ExpiresAt: expires,
+ })
+ resp := DocCollabTicketResponse{
+ Enabled: true, Token: token, Document: document, ExpiresAt: expires.UTC().Format(time.RFC3339),
+ }
+ if req.State {
+ resp.State = h.issueDescriptionCollabState(r.Context(), issue)
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// issueDescriptionCollabState is docCollabState for a description.
+func (h *Handler) issueDescriptionCollabState(ctx context.Context, issue db.Issue) string {
+ row, err := h.Queries.GetIssueDescriptionForCollab(ctx, issue.ID)
+ if err != nil || row.WorkspaceID != issue.WorkspaceID || row.Ystate == nil || !row.YstateRevision.Valid {
+ return ""
+ }
+ size := len(row.Ystate)
+ if row.YstateRevision.Int64 != row.DescriptionRevision || size > docCollabStateMaxBytes {
+ return ""
+ }
+ if size > 1<<20 && size > 4*len(row.Description.String) {
+ return ""
+ }
+ return base64.StdEncoding.EncodeToString(row.Ystate)
+}
+
+func writeIssueDescriptionMergeConflict(w http.ResponseWriter, result collab.Result) {
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": "the description overlaps edits made since its base revision",
+ "code": "issue_description_merge_conflict",
+ "conflicts": result.Conflicts,
+ "actual_revision": result.Revision,
+ "content": result.Content,
+ })
+}
+
+func writeIssueDescriptionEditFailed(w http.ResponseWriter, failure *collab.EditFailure, revision int64, content string) {
+ msg := "old_text was not found in the description"
+ switch failure.Reason {
+ case "ambiguous":
+ msg = "old_text matches more than once; quote more context or set replace_all"
+ case "empty":
+ msg = "old_text must not be empty"
+ }
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": msg,
+ "code": "issue_description_edit_failed",
+ "failure": failure,
+ "actual_revision": revision,
+ "content": content,
+ })
+}
+
+// writeIssueCollabFailure renders every non-ok result of a write through the
+// live session. It reports false for StatusOK.
+func writeIssueCollabFailure(w http.ResponseWriter, result collab.Result) bool {
+ switch result.Status {
+ case collab.StatusOK:
+ return false
+ case collab.StatusConflict:
+ writeIssueDescriptionMergeConflict(w, result)
+ case collab.StatusEditFailed:
+ failure := result.Failure
+ if failure == nil {
+ failure = &collab.EditFailure{Reason: "not_found"}
+ }
+ writeIssueDescriptionEditFailed(w, failure, result.Revision, result.Content)
+ case collab.StatusGone:
+ writeError(w, http.StatusNotFound, "issue not found")
+ case collab.StatusTooLarge:
+ writeError(w, http.StatusRequestEntityTooLarge, "description must be at most 2 MB")
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to update issue")
+ }
+ return true
+}
+
+// issueDescriptionBase resolves the description a writer started from:
+// description_base_revision when given, else the description_base text the
+// web editor sends. Neither means a whole replacement. ok is false once a
+// response has been written.
+func (h *Handler) issueDescriptionBase(w http.ResponseWriter, r *http.Request, issue db.Issue, req UpdateIssueRequest) (base *string, ok bool) {
+ if req.DescriptionBaseRevision == nil {
+ return req.DescriptionBase, true
+ }
+ rev := *req.DescriptionBaseRevision
+ switch {
+ case rev == issue.DescriptionRevision:
+ current := issue.Description.String
+ return &current, true
+ case rev >= 0 && rev < issue.DescriptionRevision:
+ content, err := h.Queries.GetIssueDescriptionRevisionContent(r.Context(), db.GetIssueDescriptionRevisionContentParams{
+ IssueID: issue.ID, Revision: rev,
+ })
+ if err == nil {
+ return &content, true
+ }
+ if !isNotFound(err) {
+ writeError(w, http.StatusInternalServerError, "failed to update issue")
+ return nil, false
+ }
+ }
+ writeRevisionConflict(w, "issue_description", issue.ID, rev, issue.DescriptionRevision)
+ return nil, false
+}
+
+// updateIssueDescriptionViaCollab sends UpdateIssue's description through the
+// live session, so it merges into what people are typing instead of
+// overwriting it. handled is false when the service is unreachable and the
+// caller should write the description directly; ok is false once a response
+// has been written.
+func (h *Handler) updateIssueDescriptionViaCollab(w http.ResponseWriter, r *http.Request, client *collab.Client, issue db.Issue, req UpdateIssueRequest, actorType, actorID string) (handled, ok bool) {
+ base, ok := h.issueDescriptionBase(w, r, issue, req)
+ if !ok {
+ return true, false
+ }
+ write := collab.WriteRequest{
+ Actor: h.collabActor(r.Context(), actorType, actorID), Content: req.Description, BaseContent: base,
+ }
+ if task := h.wakeupSourceTaskID(r); task.Valid {
+ write.TaskID = uuidToString(task)
+ }
+ result, err := client.Write(r.Context(), collab.IssueDocumentName(uuidToString(issue.ID)), write)
+ if err != nil {
+ if errors.Is(err, collab.ErrUnavailable) {
+ slog.Warn("issue description collab write failed; writing directly", "issue_id", uuidToString(issue.ID), "error", err)
+ return false, true
+ }
+ slog.Error("issue description collab write failed", append(logger.RequestAttrs(r), "issue_id", uuidToString(issue.ID), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to update issue")
+ return true, false
+ }
+ if writeIssueCollabFailure(w, result) {
+ return true, false
+ }
+ return true, true
+}
+
+// issueUpdateOnlyDescription reports whether an UpdateIssue body changes
+// nothing but the description.
+func issueUpdateOnlyDescription(raw map[string]json.RawMessage) bool {
+ for key := range raw {
+ switch key {
+ case "description", "description_base", "description_base_revision":
+ default:
+ return false
+ }
+ }
+ return true
+}
+
+type EditIssueDescriptionRequest struct {
+ Edits []collab.TextEdit `json:"edits"`
+}
+
+// EditIssueDescription applies find-and-replace edits to the description.
+// Each edit quotes the text it changes, so it lands wherever that text now is,
+// even while others are editing, and fails only when someone changed that
+// very text.
+func (h *Handler) EditIssueDescription(w http.ResponseWriter, r *http.Request) {
+ r = h.withWakeupActor(r)
+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ var req EditIssueDescriptionRequest
+ r.Body = http.MaxBytesReader(w, r.Body, docBodyMaxBytes)
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if len(req.Edits) == 0 || len(req.Edits) > docEditsMax {
+ writeError(w, http.StatusBadRequest, "edits must contain between 1 and 100 edits")
+ return
+ }
+ for i := range req.Edits {
+ req.Edits[i].OldText = sanitizeNullBytes(req.Edits[i].OldText)
+ req.Edits[i].NewText = sanitizeNullBytes(req.Edits[i].NewText)
+ if !utf8.ValidString(req.Edits[i].OldText) || !utf8.ValidString(req.Edits[i].NewText) {
+ writeError(w, http.StatusBadRequest, "edits must be valid UTF-8")
+ return
+ }
+ }
+ ctx := r.Context()
+ workspaceID := uuidToString(issue.WorkspaceID)
+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)
+ sourceTask := h.wakeupSourceTaskID(r)
+
+ if client := h.issueCollab(ctx); client != nil {
+ edit := collab.EditRequest{Actor: h.collabActor(ctx, actorType, actorID), Edits: req.Edits}
+ if sourceTask.Valid {
+ edit.TaskID = uuidToString(sourceTask)
+ }
+ result, err := client.Edit(ctx, collab.IssueDocumentName(uuidToString(issue.ID)), edit)
+ if err == nil {
+ if writeIssueCollabFailure(w, result) {
+ return
+ }
+ updated, err := h.Queries.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{ID: issue.ID, WorkspaceID: issue.WorkspaceID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load issue")
+ return
+ }
+ h.writeIssueForCaller(w, r, updated)
+ return
+ }
+ if !errors.Is(err, collab.ErrUnavailable) {
+ slog.Error("issue description collab edit failed", append(logger.RequestAttrs(r), "issue_id", uuidToString(issue.ID), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to edit issue description")
+ return
+ }
+ slog.Warn("issue description collab edit failed; editing directly", "issue_id", uuidToString(issue.ID), "error", err)
+ }
+
+ tx, err := h.beginWakeupWrite(ctx)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to edit issue description")
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ current, err := qtx.LockIssueForDescriptionUpdate(ctx, db.LockIssueForDescriptionUpdateParams{ID: issue.ID, WorkspaceID: issue.WorkspaceID})
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusNotFound, "issue not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to edit issue description")
+ }
+ return
+ }
+ content, failure := collab.ApplyTextEdits(current.Description.String, req.Edits)
+ if failure != nil {
+ writeIssueDescriptionEditFailed(w, failure, current.DescriptionRevision, current.Description.String)
+ return
+ }
+ if len(content) > issueDescriptionMaxBytes {
+ writeError(w, http.StatusRequestEntityTooLarge, "description must be at most 2 MB")
+ return
+ }
+ if content == current.Description.String {
+ h.writeIssueForCaller(w, r, current)
+ return
+ }
+ updated, err := qtx.UpdateIssue(ctx, descriptionOnlyParams(current, content, sourceTask))
+ if err == nil {
+ err = recordIssueDescriptionRevision(ctx, qtx, current, updated)
+ }
+ if err == nil {
+ err = tx.Commit(ctx)
+ }
+ if err != nil {
+ slog.Error("edit issue description failed", append(logger.RequestAttrs(r), "issue_id", uuidToString(issue.ID), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to edit issue description")
+ return
+ }
+ h.publishIssueDescriptionUpdated(ctx, current, updated, actorType, actorID, nil)
+ h.writeIssueForCaller(w, r, updated)
+}
+
+// --- Internal endpoints called by the collaboration service ---
+
+func (h *Handler) GetCollabIssue(w http.ResponseWriter, r *http.Request) {
+ issueUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "issue id")
+ if !ok {
+ return
+ }
+ row, err := h.Queries.GetIssueDescriptionForCollab(r.Context(), issueUUID)
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusNotFound, "issue not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to load issue")
+ }
+ return
+ }
+ resp := collabDocResponse{
+ WorkspaceID: uuidToString(row.WorkspaceID), Content: row.Description.String, Revision: row.DescriptionRevision,
+ }
+ if row.Ystate != nil && row.YstateRevision.Valid {
+ state := base64.StdEncoding.EncodeToString(row.Ystate)
+ resp.YState, resp.YStateRevision = &state, &row.YstateRevision.Int64
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
+
+type collabIssueStoreRequest struct {
+ BaseRevision int64 `json:"base_revision"`
+ Content string `json:"content"`
+ YState string `json:"ystate"`
+ Contributors []DocContributor `json:"contributors"`
+ TaskID string `json:"task_id"`
+ StateOnly bool `json:"state_only"`
+ // SeenMentions are the mentions ("type:id") the live session has already
+ // stored, so a mention removed and typed again in the same session does
+ // not notify twice.
+ SeenMentions []string `json:"seen_mentions"`
+ // Live marks a save of what people typed, as opposed to one agent or
+ // API write; its activity is folded per editor (see activity_listeners).
+ Live bool `json:"live"`
+}
+
+var attachmentDownloadRe = regexp.MustCompile(`/api/attachments/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/download`)
+
+// referencedAttachmentIDs lists the attachments a description links to.
+func referencedAttachmentIDs(content string) []pgtype.UUID {
+ seen := map[string]bool{}
+ var ids []pgtype.UUID
+ for _, match := range attachmentDownloadRe.FindAllStringSubmatch(content, -1) {
+ id := strings.ToLower(match[1])
+ if seen[id] {
+ continue
+ }
+ seen[id] = true
+ if parsed, err := util.ParseUUID(id); err == nil {
+ ids = append(ids, parsed)
+ }
+ }
+ return ids
+}
+
+// StoreCollabIssue saves a live description through UpdateIssue, with the
+// Yjs state behind it. The base revision is the description's own, so other
+// fields changing in between never conflict with it.
+func (h *Handler) StoreCollabIssue(w http.ResponseWriter, r *http.Request) {
+ issueUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "issue id")
+ if !ok {
+ return
+ }
+ var req collabIssueStoreRequest
+ r.Body = http.MaxBytesReader(w, r.Body, docCollabBodyMaxBytes)
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ req.Content = sanitizeNullBytes(req.Content)
+ if len(req.Content) > issueDescriptionMaxBytes {
+ writeError(w, http.StatusRequestEntityTooLarge, "description must be at most 2 MB")
+ return
+ }
+ ystate, err := base64.StdEncoding.DecodeString(req.YState)
+ if err != nil || len(ystate) == 0 {
+ writeError(w, http.StatusBadRequest, "ystate must be base64")
+ return
+ }
+ contributors := make([]DocContributor, 0, len(req.Contributors))
+ for _, c := range req.Contributors {
+ if _, err := util.ParseUUID(c.ID); err != nil || (c.Type != "member" && c.Type != "agent") {
+ writeError(w, http.StatusBadRequest, "invalid contributor")
+ return
+ }
+ contributors = append(contributors, c)
+ }
+ if len(req.SeenMentions) > issueDescriptionSeenMentionsMax {
+ req.SeenMentions = req.SeenMentions[:issueDescriptionSeenMentionsMax]
+ }
+
+ actorType, actorID := "system", ""
+ if len(contributors) > 0 {
+ actorType, actorID = contributors[0].Type, contributors[0].ID
+ }
+ var sourceTask pgtype.UUID
+ task := ""
+ if actorType == "agent" {
+ if parsed, err := util.ParseUUID(req.TaskID); err == nil {
+ sourceTask, task = parsed, uuidToString(parsed)
+ }
+ }
+ ctx := context.WithValue(r.Context(), wakeupActorKey{}, wakeupActor{actorType, actorID, task})
+ tx, err := h.beginWakeupWrite(ctx)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to store issue description")
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+ current, err := qtx.LockIssueByIDForUpdate(ctx, issueUUID)
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusNotFound, "issue not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to store issue description")
+ }
+ return
+ }
+ if current.DescriptionRevision != req.BaseRevision {
+ writeJSON(w, http.StatusConflict, map[string]any{"revision": current.DescriptionRevision, "content": current.Description.String})
+ return
+ }
+
+ updated := current
+ changed := !req.StateOnly && req.Content != current.Description.String
+ var linked int64
+ content := req.Content
+ if changed {
+ attachments, err := qtx.ListAttachmentsByIssue(ctx, db.ListAttachmentsByIssueParams{IssueID: current.ID, WorkspaceID: current.WorkspaceID})
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to store issue description")
+ return
+ }
+ // Channel media keeps its provenance markers, which the editor drops.
+ // The session saw everything stored, so a link it removed stays removed.
+ stored := current.Description.String
+ content = mergeIssueChannelMediaDescription(stored, req.Content, &stored, attachments)
+ changed = content != stored
+ }
+ if changed {
+ updated, err = qtx.UpdateIssue(ctx, descriptionOnlyParams(current, content, sourceTask))
+ if err == nil {
+ err = recordIssueDescriptionRevision(ctx, qtx, current, updated)
+ }
+ if err == nil {
+ linked, err = linkLiveDescriptionAttachments(ctx, qtx, updated, contributors)
+ }
+ if err != nil {
+ slog.Error("store issue description failed", "issue_id", uuidToString(issueUUID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to store issue description")
+ return
+ }
+ }
+ if err := qtx.UpsertIssueDescriptionCollabState(ctx, db.UpsertIssueDescriptionCollabStateParams{
+ IssueID: updated.ID, WorkspaceID: updated.WorkspaceID, Ystate: ystate, Revision: updated.DescriptionRevision,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to store issue description")
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to store issue description")
+ return
+ }
+
+ mentions := []string{}
+ if changed {
+ extra := map[string]any{"description_seen_mentions": req.SeenMentions}
+ if req.Live {
+ extra["description_live_editors"] = contributors
+ }
+ h.publishIssueDescriptionUpdated(r.Context(), current, updated, actorType, actorID, extra)
+ // After issue:updated: clients admit the snapshot before an auxiliary
+ // event at the same revision.
+ if linked > 0 {
+ h.publish(protocol.EventIssueAttachmentsChanged, uuidToString(updated.WorkspaceID), actorType, actorID, map[string]any{
+ "issue_id": uuidToString(updated.ID),
+ "issue_revision": updated.Revision,
+ })
+ }
+ for _, m := range util.ParseMentions(updated.Description.String) {
+ mentions = append(mentions, m.Type+":"+m.ID)
+ }
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"revision": updated.DescriptionRevision, "mentions": mentions})
+}
+
+// linkLiveDescriptionAttachments binds files that editors of a live session
+// uploaded and linked in the description, which the solo editor binds by
+// sending attachment_ids with its save.
+func linkLiveDescriptionAttachments(ctx context.Context, qtx *db.Queries, issue db.Issue, contributors []DocContributor) (int64, error) {
+ ids := referencedAttachmentIDs(issue.Description.String)
+ if len(ids) == 0 || len(contributors) == 0 {
+ return 0, nil
+ }
+ uploaders := make([]pgtype.UUID, 0, len(contributors))
+ for _, c := range contributors {
+ uploaders = append(uploaders, parseUUID(c.ID))
+ }
+ return qtx.LinkUnboundAttachmentsToIssue(ctx, db.LinkUnboundAttachmentsToIssueParams{
+ IssueID: issue.ID, WorkspaceID: issue.WorkspaceID, AttachmentIds: ids, UploaderIds: uploaders,
+ })
+}
diff --git a/server/internal/handler/issue_description_collab_test.go b/server/internal/handler/issue_description_collab_test.go
new file mode 100644
index 0000000000..0acf0faf26
--- /dev/null
+++ b/server/internal/handler/issue_description_collab_test.go
@@ -0,0 +1,306 @@
+package handler
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/collab"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func getIssueForTest(t *testing.T, id string) IssueResponse {
+ t.Helper()
+ var issue IssueResponse
+ testutil.Call(t, testHandler.GetIssue, withURLParam(newRequest("GET", "/api/issues/"+id, nil), "id", id)).Want(http.StatusOK).JSON(&issue)
+ return issue
+}
+
+func putIssueForTest(t *testing.T, id string, body map[string]any) *testutil.Response {
+ t.Helper()
+ return testutil.Call(t, testHandler.UpdateIssue, withURLParam(newRequest("PUT", "/api/issues/"+id, body), "id", id))
+}
+
+func storeIssueDescription(t *testing.T, id string, body map[string]any) *testutil.Response {
+ t.Helper()
+ if _, ok := body["ystate"]; !ok {
+ body["ystate"] = base64.StdEncoding.EncodeToString([]byte{1, 2, 3})
+ }
+ return testutil.Call(t, testHandler.StoreCollabIssue, withURLParam(newRequest("POST", "/internal/collab/issues/"+id+"/store", body), "id", id))
+}
+
+// captureIssueUpdates records the issue:updated payloads published for one issue.
+func captureIssueUpdates(t *testing.T, issueID string) func() []map[string]any {
+ t.Helper()
+ var mu sync.Mutex
+ var payloads []map[string]any
+ testHandler.Bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return
+ }
+ if resp, ok := payload["issue"].(IssueResponse); ok && resp.ID == issueID {
+ mu.Lock()
+ payloads = append(payloads, payload)
+ mu.Unlock()
+ }
+ })
+ return func() []map[string]any {
+ mu.Lock()
+ defer mu.Unlock()
+ return append([]map[string]any(nil), payloads...)
+ }
+}
+
+func TestStoreCollabIssueUsesTheDescriptionsOwnRevision(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ id := dbfx.Issue(t, "live description", testutil.Cols{"description": "One"})
+ updates := captureIssueUpdates(t, id)
+ start := getIssueForTest(t, id)
+ base := *start.DescriptionRevision
+
+ var stored struct {
+ Revision int64 `json:"revision"`
+ Mentions []string `json:"mentions"`
+ }
+ mention := "[@Bob](mention://member/" + testUserID + ")"
+ storeIssueDescription(t, id, map[string]any{
+ "base_revision": base, "content": "One " + mention, "live": true,
+ "contributors": []DocContributor{{Type: "member", ID: testUserID}},
+ "seen_mentions": []string{"member:someone-else"},
+ }).Want(http.StatusOK).JSON(&stored)
+ if stored.Revision != base+1 || len(stored.Mentions) != 1 || stored.Mentions[0] != "member:"+testUserID {
+ t.Fatalf("store answered %+v, want revision %d and the stored mention", stored, base+1)
+ }
+
+ // Other fields moving does not touch the description's revision, so the
+ // live session keeps saving from it.
+ putIssueForTest(t, id, map[string]any{"status": "in_progress", "priority": "high"}).Want(http.StatusOK)
+ storeIssueDescription(t, id, map[string]any{
+ "base_revision": stored.Revision, "content": "One two " + mention, "live": true,
+ "contributors": []DocContributor{{Type: "member", ID: testUserID}},
+ }).Want(http.StatusOK).JSON(&stored)
+ after := getIssueForTest(t, id)
+ if after.Description == nil || *after.Description != "One two "+mention || after.Status != "in_progress" || *after.DescriptionRevision != base+2 {
+ t.Fatalf("issue after live saves = %+v", after)
+ }
+
+ var conflict struct {
+ Revision int64 `json:"revision"`
+ Content string `json:"content"`
+ }
+ storeIssueDescription(t, id, map[string]any{
+ "base_revision": base, "content": "stale", "contributors": []DocContributor{},
+ }).Want(http.StatusConflict).JSON(&conflict)
+ if conflict.Revision != base+2 || conflict.Content != "One two "+mention {
+ t.Fatalf("stale store must report the stored description: %+v", conflict)
+ }
+
+ var live []map[string]any
+ for _, p := range updates() {
+ if _, ok := p["description_live_editors"]; ok {
+ live = append(live, p)
+ }
+ }
+ if len(live) != 2 {
+ t.Fatalf("want two live issue:updated payloads, got %d", len(live))
+ }
+ if seen, _ := live[0]["description_seen_mentions"].([]string); len(seen) != 1 || seen[0] != "member:someone-else" {
+ t.Fatalf("seen mentions must reach the listeners: %v", live[0]["description_seen_mentions"])
+ }
+
+ var loaded collabDocResponse
+ testutil.Call(t, testHandler.GetCollabIssue, withURLParam(newRequest("GET", "/internal/collab/issues/"+id, nil), "id", id)).Want(http.StatusOK).JSON(&loaded)
+ if loaded.Content != "One two "+mention || loaded.Revision != base+2 || loaded.YStateRevision == nil || *loaded.YStateRevision != base+2 {
+ t.Fatalf("internal load = %+v", loaded)
+ }
+}
+
+func TestUpdateIssueDescriptionBaseRevisionWithoutLiveEditing(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ id := dbfx.Issue(t, "base revision", testutil.Cols{"description": "Alpha"})
+ start := getIssueForTest(t, id)
+ base := *start.DescriptionRevision
+
+ var updated IssueResponse
+ putIssueForTest(t, id, map[string]any{"description": "Beta", "description_base_revision": base}).Want(http.StatusOK).JSON(&updated)
+ if *updated.DescriptionRevision != base+1 {
+ t.Fatalf("description_revision = %d, want %d", *updated.DescriptionRevision, base+1)
+ }
+ var conflict map[string]any
+ putIssueForTest(t, id, map[string]any{"description": "Gamma", "description_base_revision": base}).Want(http.StatusConflict).JSON(&conflict)
+ if conflict["code"] != "revision_conflict" || conflict["resource_type"] != "issue_description" {
+ t.Fatalf("stale base without live editing must be refused: %v", conflict)
+ }
+ // Clients that never send a base keep today's whole replacement.
+ putIssueForTest(t, id, map[string]any{"description": "Delta"}).Want(http.StatusOK)
+}
+
+func TestUpdateIssueDescriptionGoesThroughTheLiveSession(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ withFeatureFlag(t, testHandler, featureflags.IssueDescriptionLive, true)
+ id := dbfx.Issue(t, "via collab", testutil.Cols{"description": "Base"})
+ start := getIssueForTest(t, id)
+
+ var mu sync.Mutex
+ var paths []string
+ var got collab.WriteRequest
+ conflict := false
+ service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ defer mu.Unlock()
+ paths = append(paths, r.URL.Path)
+ if r.URL.Path != "/internal/documents/issue:"+id+"/write" {
+ _, _ = w.Write([]byte(`{"loaded":false}`))
+ return
+ }
+ _ = json.NewDecoder(r.Body).Decode(&got)
+ if conflict {
+ w.WriteHeader(http.StatusConflict)
+ _, _ = w.Write([]byte(`{"error":"merge_conflict","status":"conflict","revision":3,"content":"Theirs","conflicts":[{"current":"Theirs","incoming":"Mine"}]}`))
+ return
+ }
+ // The service stores through StoreCollabIssue; stand in for it.
+ stored := httptest.NewRecorder()
+ testHandler.StoreCollabIssue(stored, withURLParam(newRequest("POST", "/internal/collab/issues/"+id+"/store", map[string]any{
+ "base_revision": *start.DescriptionRevision, "content": *got.Content,
+ "ystate": base64.StdEncoding.EncodeToString([]byte{1}),
+ "contributors": []DocContributor{{Type: got.Actor.Type, ID: got.Actor.ID}},
+ }), "id", id))
+ if stored.Code != http.StatusOK {
+ t.Errorf("store: %d %s", stored.Code, stored.Body.String())
+ }
+ _, _ = w.Write([]byte(`{"status":"ok","revision":1,"content":"","title":"","merged":false}`))
+ }))
+ defer service.Close()
+ useCollab(t, service.URL)
+
+ var updated IssueResponse
+ putIssueForTest(t, id, map[string]any{
+ "description": "Mine", "description_base_revision": *start.DescriptionRevision, "status": "in_progress",
+ }).Want(http.StatusOK).JSON(&updated)
+ if got.BaseContent == nil || *got.BaseContent != "Base" || got.Actor.ID != testUserID {
+ t.Fatalf("write must carry the description at its base revision: %+v", got)
+ }
+ if updated.Description == nil || *updated.Description != "Mine" || updated.Status != "in_progress" {
+ t.Fatalf("description and status must both land: %+v", updated)
+ }
+
+ mu.Lock()
+ conflict = true
+ mu.Unlock()
+ var refused map[string]any
+ putIssueForTest(t, id, map[string]any{"description": "Other", "description_base": "Base"}).Want(http.StatusConflict).JSON(&refused)
+ if refused["code"] != "issue_description_merge_conflict" || refused["content"] != "Theirs" {
+ t.Fatalf("overlapping edits must be refused with both sides: %v", refused)
+ }
+
+ // A write pinned to the whole issue's revision stays a direct write.
+ current := getIssueForTest(t, id)
+ mu.Lock()
+ writes := len(paths)
+ mu.Unlock()
+ putIssueForTest(t, id, map[string]any{"description": "Pinned", "expected_revision": current.Revision}).Want(http.StatusOK)
+ mu.Lock()
+ defer mu.Unlock()
+ for _, p := range paths[writes:] {
+ if p == "/internal/documents/issue:"+id+"/write" {
+ t.Fatalf("expected_revision write must not go through the live session: %v", paths[writes:])
+ }
+ }
+}
+
+func TestUpdateIssueDescriptionMergesFromTheFirstRevision(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ withFeatureFlag(t, testHandler, featureflags.IssueDescriptionLive, true)
+ id := dbfx.Issue(t, "first revision", testutil.Cols{"description": "## A\n\none\n\n## B\n\ntwo"})
+ start := getIssueForTest(t, id)
+
+ var got collab.WriteRequest
+ service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewDecoder(r.Body).Decode(&got)
+ _, _ = w.Write([]byte(`{"status":"ok","revision":2,"content":"","title":"","merged":true}`))
+ }))
+ defer service.Close()
+ useCollab(t, service.URL)
+
+ // Someone types in one section before the agent, which read the issue as
+ // created, writes another.
+ storeIssueDescription(t, id, map[string]any{
+ "base_revision": *start.DescriptionRevision, "content": "## A\n\none, edited\n\n## B\n\ntwo",
+ "contributors": []DocContributor{{Type: "member", ID: testUserID}},
+ }).Want(http.StatusOK)
+ putIssueForTest(t, id, map[string]any{
+ "description": "## A\n\none\n\n## B\n\ntwo, by the agent", "description_base_revision": *start.DescriptionRevision,
+ }).Want(http.StatusOK)
+ if got.BaseContent == nil || *got.BaseContent != "## A\n\none\n\n## B\n\ntwo" {
+ t.Fatalf("a write from the first revision must merge against it: %+v", got)
+ }
+}
+
+func TestIssueCollabTicketFollowsTheFlag(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ id := dbfx.Issue(t, "ticket", testutil.Cols{"description": "Hello"})
+ // A service that is down: tickets are still signed, writes fall back.
+ service := httptest.NewServer(http.NotFoundHandler())
+ service.Close()
+ useCollab(t, service.URL)
+ ticket := func() DocCollabTicketResponse {
+ var resp DocCollabTicketResponse
+ testutil.Call(t, testHandler.CreateIssueCollabTicket, withURLParam(newRequest("POST", "/api/issues/"+id+"/collab-ticket", map[string]any{"state": true}), "id", id)).Want(http.StatusOK).JSON(&resp)
+ return resp
+ }
+ if ticket().Enabled {
+ t.Fatal("live descriptions must stay off until the flag is on")
+ }
+ withFeatureFlag(t, testHandler, featureflags.IssueDescriptionLive, true)
+ resp := ticket()
+ if !resp.Enabled || resp.Document != "issue:"+id || resp.Token == "" {
+ t.Fatalf("ticket = %+v", resp)
+ }
+ // Edits fall back to a direct write while the service is unreachable.
+ var edited IssueResponse
+ testutil.Call(t, testHandler.EditIssueDescription, withURLParam(newRequest("POST", "/api/issues/"+id+"/description/edits", map[string]any{
+ "edits": []collab.TextEdit{{OldText: "Hello", NewText: "Hello there"}},
+ }), "id", id)).Want(http.StatusOK).JSON(&edited)
+ if edited.Description == nil || *edited.Description != "Hello there" {
+ t.Fatalf("edit = %+v", edited)
+ }
+}
+
+func TestEditIssueDescriptionWithoutLiveEditing(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ id := dbfx.Issue(t, "edits", testutil.Cols{"description": "Status: draft\n\nNotes"})
+ edit := func(edits ...collab.TextEdit) *http.Request {
+ return withURLParam(newRequest("POST", "/api/issues/"+id+"/description/edits", map[string]any{"edits": edits}), "id", id)
+ }
+ var updated IssueResponse
+ testutil.Call(t, testHandler.EditIssueDescription, edit(collab.TextEdit{OldText: "draft", NewText: "ready"})).Want(http.StatusOK).JSON(&updated)
+ if updated.Description == nil || *updated.Description != "Status: ready\n\nNotes" {
+ t.Fatalf("edit not applied: %+v", updated)
+ }
+ var failed map[string]any
+ testutil.Call(t, testHandler.EditIssueDescription, edit(collab.TextEdit{OldText: "draft", NewText: "x"})).Want(http.StatusConflict).JSON(&failed)
+ if failed["code"] != "issue_description_edit_failed" || failed["content"] != "Status: ready\n\nNotes" {
+ t.Fatalf("stale quote must fail with the current text: %v", failed)
+ }
+ testutil.Call(t, testHandler.EditIssueDescription, edit()).Want(http.StatusBadRequest)
+}
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 6d92aea3d3..8887883f13 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -90,6 +90,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"issue_view": workspaceDelete,
"issue_view_preference": workspaceDelete,
"issue_dependency": workspaceDelete,
+ "issue_description_collab_state": workspaceDelete,
+ "issue_description_revision": workspaceDelete,
"issue_label": workspaceDelete,
"issue_property": workspaceDelete,
"issue_pr_automation": workspaceDelete,
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 61a8fcee10..933540a1d0 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -8301,18 +8301,19 @@ func IssueToMap(issue db.Issue, issuePrefix string) map[string]any {
"parent_issue_id": util.UUIDToPtr(issue.ParentIssueID),
// Mirrors handler.IssueResponse.DuplicateOf. Null is only true for a
// row with no live mark; IssueToMapResolved resolves it for the rest.
- "duplicate_of": nil,
- "project_id": util.UUIDToPtr(issue.ProjectID),
- "position": issue.Position,
- "stage": util.Int4ToPtr(issue.Stage),
- "start_date": util.DateToPtr(issue.StartDate),
- "due_date": util.DateToPtr(issue.DueDate),
- "created_at": util.TimestampToString(issue.CreatedAt),
- "updated_at": util.TimestampToString(issue.UpdatedAt),
- "last_activity_at": util.TimestampToNanoPtr(issue.LastActivityAt),
- "revision": issue.Revision,
- "metadata": util.JSONObjectOrEmpty(issue.Metadata),
- "properties": util.JSONObjectOrEmpty(issue.Properties),
+ "duplicate_of": nil,
+ "project_id": util.UUIDToPtr(issue.ProjectID),
+ "position": issue.Position,
+ "stage": util.Int4ToPtr(issue.Stage),
+ "start_date": util.DateToPtr(issue.StartDate),
+ "due_date": util.DateToPtr(issue.DueDate),
+ "created_at": util.TimestampToString(issue.CreatedAt),
+ "updated_at": util.TimestampToString(issue.UpdatedAt),
+ "last_activity_at": util.TimestampToNanoPtr(issue.LastActivityAt),
+ "revision": issue.Revision,
+ "description_revision": issue.DescriptionRevision,
+ "metadata": util.JSONObjectOrEmpty(issue.Metadata),
+ "properties": util.JSONObjectOrEmpty(issue.Properties),
}
}
diff --git a/server/migrations/723_issue_description_collab.down.sql b/server/migrations/723_issue_description_collab.down.sql
new file mode 100644
index 0000000000..1f8bd53395
--- /dev/null
+++ b/server/migrations/723_issue_description_collab.down.sql
@@ -0,0 +1,3 @@
+DROP TABLE IF EXISTS issue_description_revision;
+DROP TABLE IF EXISTS issue_description_collab_state;
+ALTER TABLE issue DROP COLUMN IF EXISTS description_revision;
diff --git a/server/migrations/723_issue_description_collab.up.sql b/server/migrations/723_issue_description_collab.up.sql
new file mode 100644
index 0000000000..5134c50839
--- /dev/null
+++ b/server/migrations/723_issue_description_collab.up.sql
@@ -0,0 +1,28 @@
+-- Live co-editing of issue descriptions (MUL-9778).
+--
+-- description_revision counts changes to the description alone. Live saves
+-- and merges are checked against it instead of the issue-wide revision, which
+-- every status, assignee, comment or metadata write also advances. A constant
+-- default keeps the column add metadata-only.
+--
+-- issue_description_collab_state is the Yjs state behind the stored
+-- description; issue_description_revision keeps the description of recent
+-- revisions, so a write based on an older one is merged instead of refused.
+-- Primary keys are built concurrently in 720–723.
+ALTER TABLE issue ADD COLUMN IF NOT EXISTS description_revision BIGINT NOT NULL DEFAULT 0;
+
+CREATE TABLE IF NOT EXISTS issue_description_collab_state (
+ issue_id UUID NOT NULL,
+ workspace_id UUID NOT NULL,
+ ystate BYTEA NOT NULL,
+ revision BIGINT NOT NULL,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE TABLE IF NOT EXISTS issue_description_revision (
+ issue_id UUID NOT NULL,
+ workspace_id UUID NOT NULL,
+ revision BIGINT NOT NULL,
+ content TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/724_issue_description_collab_state_pkey_index.down.sql b/server/migrations/724_issue_description_collab_state_pkey_index.down.sql
new file mode 100644
index 0000000000..fc18a17120
--- /dev/null
+++ b/server/migrations/724_issue_description_collab_state_pkey_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS issue_description_collab_state_pkey_idx;
diff --git a/server/migrations/724_issue_description_collab_state_pkey_index.up.sql b/server/migrations/724_issue_description_collab_state_pkey_index.up.sql
new file mode 100644
index 0000000000..d277f05c30
--- /dev/null
+++ b/server/migrations/724_issue_description_collab_state_pkey_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS issue_description_collab_state_pkey_idx ON issue_description_collab_state (issue_id);
diff --git a/server/migrations/725_issue_description_collab_state_pkey.down.sql b/server/migrations/725_issue_description_collab_state_pkey.down.sql
new file mode 100644
index 0000000000..c006b59034
--- /dev/null
+++ b/server/migrations/725_issue_description_collab_state_pkey.down.sql
@@ -0,0 +1 @@
+ALTER TABLE issue_description_collab_state DROP CONSTRAINT IF EXISTS issue_description_collab_state_pkey;
diff --git a/server/migrations/725_issue_description_collab_state_pkey.up.sql b/server/migrations/725_issue_description_collab_state_pkey.up.sql
new file mode 100644
index 0000000000..fff7a45d84
--- /dev/null
+++ b/server/migrations/725_issue_description_collab_state_pkey.up.sql
@@ -0,0 +1 @@
+ALTER TABLE issue_description_collab_state ADD CONSTRAINT issue_description_collab_state_pkey PRIMARY KEY USING INDEX issue_description_collab_state_pkey_idx;
diff --git a/server/migrations/726_issue_description_revision_pkey_index.down.sql b/server/migrations/726_issue_description_revision_pkey_index.down.sql
new file mode 100644
index 0000000000..54d0b493f8
--- /dev/null
+++ b/server/migrations/726_issue_description_revision_pkey_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS issue_description_revision_pkey_idx;
diff --git a/server/migrations/726_issue_description_revision_pkey_index.up.sql b/server/migrations/726_issue_description_revision_pkey_index.up.sql
new file mode 100644
index 0000000000..3db3bcd4a4
--- /dev/null
+++ b/server/migrations/726_issue_description_revision_pkey_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS issue_description_revision_pkey_idx ON issue_description_revision (issue_id, revision);
diff --git a/server/migrations/727_issue_description_revision_pkey.down.sql b/server/migrations/727_issue_description_revision_pkey.down.sql
new file mode 100644
index 0000000000..81986fcaad
--- /dev/null
+++ b/server/migrations/727_issue_description_revision_pkey.down.sql
@@ -0,0 +1 @@
+ALTER TABLE issue_description_revision DROP CONSTRAINT IF EXISTS issue_description_revision_pkey;
diff --git a/server/migrations/727_issue_description_revision_pkey.up.sql b/server/migrations/727_issue_description_revision_pkey.up.sql
new file mode 100644
index 0000000000..b824585a28
--- /dev/null
+++ b/server/migrations/727_issue_description_revision_pkey.up.sql
@@ -0,0 +1 @@
+ALTER TABLE issue_description_revision ADD CONSTRAINT issue_description_revision_pkey PRIMARY KEY USING INDEX issue_description_revision_pkey_idx;
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 563bd0896c..5f6f0d192f 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -64,7 +64,7 @@ SET duplicate_of_issue_id = NULL,
WHERE workspace_id = $1
AND duplicate_of_issue_id = $2::uuid
AND NOT COALESCE(id = ANY($3::uuid[]), false)
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision
`
type ClearIssueDuplicatesOfParams struct {
@@ -117,6 +117,7 @@ func (q *Queries) ClearIssueDuplicatesOf(ctx context.Context, arg ClearIssueDupl
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
); err != nil {
return nil, err
}
@@ -272,7 +273,7 @@ INSERT INTO issue (
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
$16, COALESCE($17::jsonb, '{}'::jsonb), now(), COALESCE($18::uuid, gen_random_uuid())
-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id
+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision
`
type CreateIssueParams struct {
@@ -350,6 +351,7 @@ func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
@@ -363,7 +365,7 @@ INSERT INTO issue (
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
$16, $17, $18, COALESCE($19::jsonb, '{}'::jsonb), now(), COALESCE($20::uuid, gen_random_uuid()), $21
-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id
+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision
`
type CreateIssueWithOriginParams struct {
@@ -447,6 +449,7 @@ func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWith
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
@@ -493,6 +496,12 @@ cleared_environment_configs AS (
),
cleared_task_context_receipts AS (
DELETE FROM task_context_receipt WHERE issue_id IN (SELECT target.id FROM target)
+),
+cleared_description_collab_state AS (
+ DELETE FROM issue_description_collab_state WHERE issue_id IN (SELECT target.id FROM target)
+),
+cleared_description_revisions AS (
+ DELETE FROM issue_description_revision WHERE issue_id IN (SELECT target.id FROM target)
)
DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target)
`
@@ -573,7 +582,7 @@ SET parent_issue_id = NULL,
WHERE workspace_id = $1
AND parent_issue_id = $2
AND NOT COALESCE(id = ANY($3::uuid[]), false)
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision
`
type DetachDirectChildIssuesParams struct {
@@ -623,6 +632,7 @@ func (q *Queries) DetachDirectChildIssues(ctx context.Context, arg DetachDirectC
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
); err != nil {
return nil, err
}
@@ -635,7 +645,7 @@ func (q *Queries) DetachDirectChildIssues(ctx context.Context, arg DetachDirectC
}
const findActiveDuplicateIssue = `-- name: FindActiveDuplicateIssue :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE workspace_id = $1
-- Negate only known terminal keys so an unknown legacy key remains active.
AND NOT (status = ANY($2::text[]))
@@ -699,12 +709,13 @@ func (q *Queries) FindActiveDuplicateIssue(ctx context.Context, arg FindActiveDu
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
const findRecentAutopilotDuplicateIssue = `-- name: FindRecentAutopilotDuplicateIssue :one
-SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id FROM issue i
+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id, i.description_revision FROM issue i
WHERE i.workspace_id = $1
-- Negate only known terminal keys so an unknown legacy key remains active.
AND NOT (i.status = ANY($3::text[]))
@@ -779,12 +790,13 @@ func (q *Queries) FindRecentAutopilotDuplicateIssue(ctx context.Context, arg Fin
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
const getIssue = `-- name: GetIssue :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE id = $1
`
@@ -823,12 +835,13 @@ func (q *Queries) GetIssue(ctx context.Context, id pgtype.UUID) (Issue, error) {
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
const getIssueByNumber = `-- name: GetIssueByNumber :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE workspace_id = $1 AND number = $2
`
@@ -872,12 +885,13 @@ func (q *Queries) GetIssueByNumber(ctx context.Context, arg GetIssueByNumberPara
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
const getIssueByOrigin = `-- name: GetIssueByOrigin :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE workspace_id = $1
AND origin_type = $2
AND origin_id = $3
@@ -930,6 +944,7 @@ func (q *Queries) GetIssueByOrigin(ctx context.Context, arg GetIssueByOriginPara
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
@@ -954,7 +969,7 @@ func (q *Queries) GetIssueGCStatus(ctx context.Context, id pgtype.UUID) (GetIssu
}
const getIssueInWorkspace = `-- name: GetIssueInWorkspace :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE id = $1 AND workspace_id = $2
`
@@ -998,6 +1013,7 @@ func (q *Queries) GetIssueInWorkspace(ctx context.Context, arg GetIssueInWorkspa
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
@@ -1097,7 +1113,7 @@ func (q *Queries) IssueHasDuplicates(ctx context.Context, arg IssueHasDuplicates
}
const listChildIssues = `-- name: ListChildIssues :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE parent_issue_id = $1
ORDER BY number ASC
`
@@ -1149,6 +1165,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
); err != nil {
return nil, err
}
@@ -1161,7 +1178,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID
}
const listChildrenByParents = `-- name: ListChildrenByParents :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE workspace_id = $1
AND parent_issue_id = ANY($2::uuid[])
ORDER BY parent_issue_id, number ASC
@@ -1220,6 +1237,7 @@ func (q *Queries) ListChildrenByParents(ctx context.Context, arg ListChildrenByP
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
); err != nil {
return nil, err
}
@@ -1232,7 +1250,7 @@ func (q *Queries) ListChildrenByParents(ctx context.Context, arg ListChildrenByP
}
const listIssueDuplicates = `-- name: ListIssueDuplicates :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE workspace_id = $1
AND duplicate_of_issue_id = $2::uuid
AND status = 'cancelled'
@@ -1285,6 +1303,7 @@ func (q *Queries) ListIssueDuplicates(ctx context.Context, arg ListIssueDuplicat
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
); err != nil {
return nil, err
}
@@ -1816,7 +1835,7 @@ func (q *Queries) LockIssueForDelete(ctx context.Context, arg LockIssueForDelete
}
const lockIssueForDescriptionUpdate = `-- name: LockIssueForDescriptionUpdate :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE id = $1 AND workspace_id = $2
FOR UPDATE
`
@@ -1865,6 +1884,7 @@ func (q *Queries) LockIssueForDescriptionUpdate(ctx context.Context, arg LockIss
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
@@ -1960,10 +1980,11 @@ SET description = CASE
ELSE description || E'\n\n' || $3
END,
revision = revision + 1,
+ description_revision = description_revision + 1,
updated_at = now()
WHERE id = $4
AND workspace_id = $5
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision
`
type MaterializeIssueChannelMediaMarkdownParams struct {
@@ -2022,6 +2043,7 @@ func (q *Queries) MaterializeIssueChannelMediaMarkdown(ctx context.Context, arg
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
@@ -2116,7 +2138,7 @@ WITH wakeup_source AS MATERIALIZED (SELECT set_config('multica.source_task_id',
-- did_change/did_activity would be decided against the pre-wait row too.
-- Materialized so the locking clause is never inlined away.
SELECT
- i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id,
+ i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id, i.description_revision,
COALESCE($4::text, i.title) AS next_title,
COALESCE($5::text, i.description) AS next_description,
COALESCE($6::text, i.status) AS next_status,
@@ -2174,7 +2196,7 @@ WITH wakeup_source AS MATERIALIZED (SELECT set_config('multica.source_task_id',
FOR UPDATE
), changed AS (
SELECT
- candidate.id, candidate.workspace_id, candidate.title, candidate.description, candidate.status, candidate.priority, candidate.assignee_type, candidate.assignee_id, candidate.creator_type, candidate.creator_id, candidate.parent_issue_id, candidate.acceptance_criteria, candidate.context_refs, candidate.position, candidate.due_date, candidate.created_at, candidate.updated_at, candidate.number, candidate.project_id, candidate.origin_type, candidate.origin_id, candidate.first_executed_at, candidate.start_date, candidate.metadata, candidate.stage, candidate.properties, candidate.revision, candidate.last_activity_at, candidate.triage_state, candidate.duplicate_of_issue_id, candidate.requester_user_id, candidate.next_title, candidate.next_description, candidate.next_status, candidate.next_priority, candidate.next_assignee_type, candidate.next_assignee_id, candidate.next_position, candidate.next_start_date, candidate.next_due_date, candidate.next_parent_issue_id, candidate.next_project_id, candidate.next_stage, candidate.next_duplicate_of_issue_id,
+ candidate.id, candidate.workspace_id, candidate.title, candidate.description, candidate.status, candidate.priority, candidate.assignee_type, candidate.assignee_id, candidate.creator_type, candidate.creator_id, candidate.parent_issue_id, candidate.acceptance_criteria, candidate.context_refs, candidate.position, candidate.due_date, candidate.created_at, candidate.updated_at, candidate.number, candidate.project_id, candidate.origin_type, candidate.origin_id, candidate.first_executed_at, candidate.start_date, candidate.metadata, candidate.stage, candidate.properties, candidate.revision, candidate.last_activity_at, candidate.triage_state, candidate.duplicate_of_issue_id, candidate.requester_user_id, candidate.description_revision, candidate.next_title, candidate.next_description, candidate.next_status, candidate.next_priority, candidate.next_assignee_type, candidate.next_assignee_id, candidate.next_position, candidate.next_start_date, candidate.next_due_date, candidate.next_parent_issue_id, candidate.next_project_id, candidate.next_stage, candidate.next_duplicate_of_issue_id,
ROW(
title, description, status, priority, assignee_type, assignee_id,
position, start_date, due_date, parent_issue_id, project_id, stage,
@@ -2212,6 +2234,8 @@ UPDATE issue AS i SET
stage = changed.next_stage,
duplicate_of_issue_id = changed.next_duplicate_of_issue_id,
revision = i.revision + changed.did_change::integer,
+ description_revision = i.description_revision
+ + (changed.next_description IS DISTINCT FROM changed.description)::integer,
last_activity_at = CASE WHEN changed.did_activity
THEN GREATEST(COALESCE(i.last_activity_at, i.updated_at), now())
ELSE i.last_activity_at
@@ -2224,7 +2248,7 @@ WHERE i.id = changed.id
-- from the same snapshot; EvalPlanQual re-evaluates this target-row predicate
-- after waiting for the first writer, leaving the stale writer with 0 rows.
AND ($2::bigint IS NULL OR i.revision = $2::bigint)
-RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id
+RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id, i.description_revision
`
type UpdateIssueParams struct {
@@ -2298,6 +2322,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
@@ -2324,7 +2349,7 @@ UPDATE issue AS i SET
updated_at = now()
FROM wakeup_source
WHERE i.id = $1 AND i.workspace_id = $3
-RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id
+RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id, i.description_revision
`
type UpdateIssueStatusParams struct {
@@ -2379,6 +2404,7 @@ func (q *Queries) UpdateIssueStatus(ctx context.Context, arg UpdateIssueStatusPa
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
diff --git a/server/pkg/db/generated/issue_description_collab.sql.go b/server/pkg/db/generated/issue_description_collab.sql.go
new file mode 100644
index 0000000000..44c5a5dd4b
--- /dev/null
+++ b/server/pkg/db/generated/issue_description_collab.sql.go
@@ -0,0 +1,230 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: issue_description_collab.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const getIssueDescriptionForCollab = `-- name: GetIssueDescriptionForCollab :one
+SELECT i.workspace_id, i.description, i.description_revision,
+ s.ystate AS ystate, s.revision AS ystate_revision
+FROM issue i
+LEFT JOIN issue_description_collab_state s ON s.issue_id = i.id
+WHERE i.id = $1
+`
+
+type GetIssueDescriptionForCollabRow struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Description pgtype.Text `json:"description"`
+ DescriptionRevision int64 `json:"description_revision"`
+ Ystate []byte `json:"ystate"`
+ YstateRevision pgtype.Int8 `json:"ystate_revision"`
+}
+
+// The collaboration service's view of a description: the stored text plus the
+// Yjs state last saved with it, which is only reusable at the same revision.
+func (q *Queries) GetIssueDescriptionForCollab(ctx context.Context, id pgtype.UUID) (GetIssueDescriptionForCollabRow, error) {
+ row := q.db.QueryRow(ctx, getIssueDescriptionForCollab, id)
+ var i GetIssueDescriptionForCollabRow
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.Description,
+ &i.DescriptionRevision,
+ &i.Ystate,
+ &i.YstateRevision,
+ )
+ return i, err
+}
+
+const getIssueDescriptionRevisionContent = `-- name: GetIssueDescriptionRevisionContent :one
+SELECT content FROM issue_description_revision
+WHERE issue_id = $1 AND revision = $2
+`
+
+type GetIssueDescriptionRevisionContentParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ Revision int64 `json:"revision"`
+}
+
+func (q *Queries) GetIssueDescriptionRevisionContent(ctx context.Context, arg GetIssueDescriptionRevisionContentParams) (string, error) {
+ row := q.db.QueryRow(ctx, getIssueDescriptionRevisionContent, arg.IssueID, arg.Revision)
+ var content string
+ err := row.Scan(&content)
+ return content, err
+}
+
+const hasRecentLiveDescriptionActivity = `-- name: HasRecentLiveDescriptionActivity :one
+SELECT EXISTS (
+ SELECT 1 FROM activity_log
+ WHERE issue_id = $1
+ AND action = 'description_updated'
+ AND actor_type = $2
+ AND actor_id = $3
+ AND details->>'live' = 'true'
+ AND created_at > now() - interval '30 minutes'
+)
+`
+
+type HasRecentLiveDescriptionActivityParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ ActorType pgtype.Text `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+}
+
+// A live editing session records one description_updated entry per editor:
+// saves within 30 minutes of that editor's last live entry add none.
+func (q *Queries) HasRecentLiveDescriptionActivity(ctx context.Context, arg HasRecentLiveDescriptionActivityParams) (bool, error) {
+ row := q.db.QueryRow(ctx, hasRecentLiveDescriptionActivity, arg.IssueID, arg.ActorType, arg.ActorID)
+ var exists bool
+ err := row.Scan(&exists)
+ return exists, err
+}
+
+const insertIssueDescriptionRevision = `-- name: InsertIssueDescriptionRevision :exec
+INSERT INTO issue_description_revision (issue_id, workspace_id, revision, content)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (issue_id, revision) DO UPDATE SET content = EXCLUDED.content
+`
+
+type InsertIssueDescriptionRevisionParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Revision int64 `json:"revision"`
+ Content string `json:"content"`
+}
+
+func (q *Queries) InsertIssueDescriptionRevision(ctx context.Context, arg InsertIssueDescriptionRevisionParams) error {
+ _, err := q.db.Exec(ctx, insertIssueDescriptionRevision,
+ arg.IssueID,
+ arg.WorkspaceID,
+ arg.Revision,
+ arg.Content,
+ )
+ return err
+}
+
+const linkUnboundAttachmentsToIssue = `-- name: LinkUnboundAttachmentsToIssue :execrows
+UPDATE attachment SET issue_id = $1
+WHERE workspace_id = $2
+ AND id = ANY($3::uuid[])
+ AND issue_id IS NULL
+ AND comment_id IS NULL
+ AND chat_session_id IS NULL
+ AND chat_message_id IS NULL
+ AND source_context_id IS NULL
+ AND uploader_id = ANY($4::uuid[])
+`
+
+type LinkUnboundAttachmentsToIssueParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AttachmentIds []pgtype.UUID `json:"attachment_ids"`
+ UploaderIds []pgtype.UUID `json:"uploader_ids"`
+}
+
+// Binds files uploaded into a live description to its issue, as the solo
+// editor does with attachment_ids on save. Only files one of the editors
+// uploaded and nothing owns yet.
+func (q *Queries) LinkUnboundAttachmentsToIssue(ctx context.Context, arg LinkUnboundAttachmentsToIssueParams) (int64, error) {
+ result, err := q.db.Exec(ctx, linkUnboundAttachmentsToIssue,
+ arg.IssueID,
+ arg.WorkspaceID,
+ arg.AttachmentIds,
+ arg.UploaderIds,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const lockIssueByIDForUpdate = `-- name: LockIssueByIDForUpdate :one
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue WHERE id = $1 FOR UPDATE
+`
+
+func (q *Queries) LockIssueByIDForUpdate(ctx context.Context, id pgtype.UUID) (Issue, error) {
+ row := q.db.QueryRow(ctx, lockIssueByIDForUpdate, id)
+ var i Issue
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Status,
+ &i.Priority,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.CreatorType,
+ &i.CreatorID,
+ &i.ParentIssueID,
+ &i.AcceptanceCriteria,
+ &i.ContextRefs,
+ &i.Position,
+ &i.DueDate,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Number,
+ &i.ProjectID,
+ &i.OriginType,
+ &i.OriginID,
+ &i.FirstExecutedAt,
+ &i.StartDate,
+ &i.Metadata,
+ &i.Stage,
+ &i.Properties,
+ &i.Revision,
+ &i.LastActivityAt,
+ &i.TriageState,
+ &i.DuplicateOfIssueID,
+ &i.RequesterUserID,
+ &i.DescriptionRevision,
+ )
+ return i, err
+}
+
+const pruneIssueDescriptionRevisions = `-- name: PruneIssueDescriptionRevisions :exec
+DELETE FROM issue_description_revision
+WHERE issue_id = $1 AND revision < $2
+`
+
+type PruneIssueDescriptionRevisionsParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ KeepFrom int64 `json:"keep_from"`
+}
+
+func (q *Queries) PruneIssueDescriptionRevisions(ctx context.Context, arg PruneIssueDescriptionRevisionsParams) error {
+ _, err := q.db.Exec(ctx, pruneIssueDescriptionRevisions, arg.IssueID, arg.KeepFrom)
+ return err
+}
+
+const upsertIssueDescriptionCollabState = `-- name: UpsertIssueDescriptionCollabState :exec
+INSERT INTO issue_description_collab_state (issue_id, workspace_id, ystate, revision)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (issue_id) DO UPDATE SET
+ ystate = EXCLUDED.ystate,
+ revision = EXCLUDED.revision,
+ updated_at = now()
+`
+
+type UpsertIssueDescriptionCollabStateParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Ystate []byte `json:"ystate"`
+ Revision int64 `json:"revision"`
+}
+
+func (q *Queries) UpsertIssueDescriptionCollabState(ctx context.Context, arg UpsertIssueDescriptionCollabStateParams) error {
+ _, err := q.db.Exec(ctx, upsertIssueDescriptionCollabState,
+ arg.IssueID,
+ arg.WorkspaceID,
+ arg.Ystate,
+ arg.Revision,
+ )
+ return err
+}
diff --git a/server/pkg/db/generated/issue_property.sql.go b/server/pkg/db/generated/issue_property.sql.go
index 54207130e0..f26a1c6623 100644
--- a/server/pkg/db/generated/issue_property.sql.go
+++ b/server/pkg/db/generated/issue_property.sql.go
@@ -126,7 +126,7 @@ SET properties = properties - $1::text,
END,
updated_at = CASE WHEN properties ? $1::text THEN now() ELSE updated_at END
WHERE id = $2::uuid AND workspace_id = $3::uuid
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision
`
type DeleteIssuePropertyValueParams struct {
@@ -170,6 +170,7 @@ func (q *Queries) DeleteIssuePropertyValue(ctx context.Context, arg DeleteIssueP
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
@@ -263,7 +264,7 @@ SET properties = jsonb_set(properties, ARRAY[$1::text], $2::jsonb, true),
END,
updated_at = CASE WHEN properties -> $1::text IS DISTINCT FROM $2::jsonb THEN now() ELSE updated_at END
WHERE id = $3::uuid AND workspace_id = $4::uuid
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision
`
type SetIssuePropertyValueParams struct {
@@ -316,6 +317,7 @@ func (q *Queries) SetIssuePropertyValue(ctx context.Context, arg SetIssuePropert
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
diff --git a/server/pkg/db/generated/issue_workflow.sql.go b/server/pkg/db/generated/issue_workflow.sql.go
index a1ee50670b..29076b6b86 100644
--- a/server/pkg/db/generated/issue_workflow.sql.go
+++ b/server/pkg/db/generated/issue_workflow.sql.go
@@ -499,7 +499,7 @@ WHERE i.workspace_id = $2::uuid
AND i.project_id = ANY($3::uuid[])
AND i.status = $4::text
AND i.status <> $1::text
-RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id
+RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id, i.description_revision
`
type RemapProjectIssueStatusParams struct {
@@ -561,6 +561,7 @@ func (q *Queries) RemapProjectIssueStatus(ctx context.Context, arg RemapProjectI
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index d12ad16ff7..57153b3b3d 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1105,37 +1105,38 @@ type InstanceTelemetryState struct {
}
type Issue struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Title string `json:"title"`
- Description pgtype.Text `json:"description"`
- Status string `json:"status"`
- Priority string `json:"priority"`
- AssigneeType pgtype.Text `json:"assignee_type"`
- AssigneeID pgtype.UUID `json:"assignee_id"`
- CreatorType string `json:"creator_type"`
- CreatorID pgtype.UUID `json:"creator_id"`
- ParentIssueID pgtype.UUID `json:"parent_issue_id"`
- AcceptanceCriteria []byte `json:"acceptance_criteria"`
- ContextRefs []byte `json:"context_refs"`
- Position float64 `json:"position"`
- DueDate pgtype.Date `json:"due_date"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- Number int32 `json:"number"`
- ProjectID pgtype.UUID `json:"project_id"`
- OriginType pgtype.Text `json:"origin_type"`
- OriginID pgtype.UUID `json:"origin_id"`
- FirstExecutedAt pgtype.Timestamptz `json:"first_executed_at"`
- StartDate pgtype.Date `json:"start_date"`
- Metadata []byte `json:"metadata"`
- Stage pgtype.Int4 `json:"stage"`
- Properties []byte `json:"properties"`
- Revision int64 `json:"revision"`
- LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
- TriageState pgtype.Text `json:"triage_state"`
- DuplicateOfIssueID pgtype.UUID `json:"duplicate_of_issue_id"`
- RequesterUserID pgtype.UUID `json:"requester_user_id"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Title string `json:"title"`
+ Description pgtype.Text `json:"description"`
+ Status string `json:"status"`
+ Priority string `json:"priority"`
+ AssigneeType pgtype.Text `json:"assignee_type"`
+ AssigneeID pgtype.UUID `json:"assignee_id"`
+ CreatorType string `json:"creator_type"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ ParentIssueID pgtype.UUID `json:"parent_issue_id"`
+ AcceptanceCriteria []byte `json:"acceptance_criteria"`
+ ContextRefs []byte `json:"context_refs"`
+ Position float64 `json:"position"`
+ DueDate pgtype.Date `json:"due_date"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ Number int32 `json:"number"`
+ ProjectID pgtype.UUID `json:"project_id"`
+ OriginType pgtype.Text `json:"origin_type"`
+ OriginID pgtype.UUID `json:"origin_id"`
+ FirstExecutedAt pgtype.Timestamptz `json:"first_executed_at"`
+ StartDate pgtype.Date `json:"start_date"`
+ Metadata []byte `json:"metadata"`
+ Stage pgtype.Int4 `json:"stage"`
+ Properties []byte `json:"properties"`
+ Revision int64 `json:"revision"`
+ LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`
+ TriageState pgtype.Text `json:"triage_state"`
+ DuplicateOfIssueID pgtype.UUID `json:"duplicate_of_issue_id"`
+ RequesterUserID pgtype.UUID `json:"requester_user_id"`
+ DescriptionRevision int64 `json:"description_revision"`
}
type IssueChildEvent struct {
@@ -1157,6 +1158,22 @@ type IssueDependency struct {
Type string `json:"type"`
}
+type IssueDescriptionCollabState struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Ystate []byte `json:"ystate"`
+ Revision int64 `json:"revision"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
+type IssueDescriptionRevision struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Revision int64 `json:"revision"`
+ Content string `json:"content"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type IssueEnvironment struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
diff --git a/server/pkg/db/generated/pr_automation.sql.go b/server/pkg/db/generated/pr_automation.sql.go
index e3fc7e6c3e..4f8eb2747f 100644
--- a/server/pkg/db/generated/pr_automation.sql.go
+++ b/server/pkg/db/generated/pr_automation.sql.go
@@ -173,7 +173,7 @@ WHERE i.id = $1
JOIN vcs_pull_request pr ON pr.id = ipr.pull_request_id
WHERE ipr.issue_id = i.id AND pr.state <> 'merged'
)
-RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id
+RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id, i.description_revision
`
type MoveIssueFromPullRequestsParams struct {
@@ -229,6 +229,7 @@ func (q *Queries) MoveIssueFromPullRequests(ctx context.Context, arg MoveIssueFr
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
diff --git a/server/pkg/db/generated/qoder_issue_lifecycle.sql.go b/server/pkg/db/generated/qoder_issue_lifecycle.sql.go
index b7483b0c95..93c1726450 100644
--- a/server/pkg/db/generated/qoder_issue_lifecycle.sql.go
+++ b/server/pkg/db/generated/qoder_issue_lifecycle.sql.go
@@ -12,7 +12,7 @@ import (
)
const lockQoderTaskIssue = `-- name: LockQoderTaskIssue :one
-SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id FROM issue i
+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id, i.requester_user_id, i.description_revision FROM issue i
JOIN agent_task_queue t ON t.issue_id = i.id
JOIN agent_runtime r ON r.id = t.runtime_id AND r.workspace_id = i.workspace_id
WHERE t.id = $1 AND r.provider = 'qoder_cloud'
@@ -60,6 +60,7 @@ func (q *Queries) LockQoderTaskIssue(ctx context.Context, taskID pgtype.UUID) (I
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
diff --git a/server/pkg/db/generated/search_index.sql.go b/server/pkg/db/generated/search_index.sql.go
index 1947eb4c6d..08a8fa98fc 100644
--- a/server/pkg/db/generated/search_index.sql.go
+++ b/server/pkg/db/generated/search_index.sql.go
@@ -261,7 +261,7 @@ func (q *Queries) ListSearchIndexCommentsByIssues(ctx context.Context, arg ListS
}
const listSearchIndexIssuesByIDs = `-- name: ListSearchIndexIssuesByIDs :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE workspace_id = $1 AND id = ANY($2::uuid[])
`
@@ -311,6 +311,7 @@ func (q *Queries) ListSearchIndexIssuesByIDs(ctx context.Context, arg ListSearch
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
); err != nil {
return nil, err
}
@@ -323,7 +324,7 @@ func (q *Queries) ListSearchIndexIssuesByIDs(ctx context.Context, arg ListSearch
}
const listSearchIndexIssuesPage = `-- name: ListSearchIndexIssuesPage :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue
WHERE workspace_id = $1 AND number > $2
ORDER BY number
LIMIT $3
@@ -377,6 +378,7 @@ func (q *Queries) ListSearchIndexIssuesPage(ctx context.Context, arg ListSearchI
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/system_wakeup.sql.go b/server/pkg/db/generated/system_wakeup.sql.go
index 54101f4b6e..2f809caaa9 100644
--- a/server/pkg/db/generated/system_wakeup.sql.go
+++ b/server/pkg/db/generated/system_wakeup.sql.go
@@ -423,7 +423,7 @@ func (q *Queries) ListChildConditionWakeups(ctx context.Context, issueID pgtype.
}
const listParentsWithoutSystemWakeup = `-- name: ListParentsWithoutSystemWakeup :many
-SELECT p.id, p.workspace_id, p.title, p.description, p.status, p.priority, p.assignee_type, p.assignee_id, p.creator_type, p.creator_id, p.parent_issue_id, p.acceptance_criteria, p.context_refs, p.position, p.due_date, p.created_at, p.updated_at, p.number, p.project_id, p.origin_type, p.origin_id, p.first_executed_at, p.start_date, p.metadata, p.stage, p.properties, p.revision, p.last_activity_at, p.triage_state, p.duplicate_of_issue_id, p.requester_user_id FROM (SELECT DISTINCT c.parent_issue_id AS id FROM issue c WHERE c.parent_issue_id IS NOT NULL) parents
+SELECT p.id, p.workspace_id, p.title, p.description, p.status, p.priority, p.assignee_type, p.assignee_id, p.creator_type, p.creator_id, p.parent_issue_id, p.acceptance_criteria, p.context_refs, p.position, p.due_date, p.created_at, p.updated_at, p.number, p.project_id, p.origin_type, p.origin_id, p.first_executed_at, p.start_date, p.metadata, p.stage, p.properties, p.revision, p.last_activity_at, p.triage_state, p.duplicate_of_issue_id, p.requester_user_id, p.description_revision FROM (SELECT DISTINCT c.parent_issue_id AS id FROM issue c WHERE c.parent_issue_id IS NOT NULL) parents
JOIN issue p ON p.id=parents.id
WHERE NOT EXISTS(SELECT 1 FROM issue_wakeup w WHERE w.issue_id=p.id AND w.system_rule= $1)
AND p.status NOT IN ('done','cancelled')
@@ -478,6 +478,7 @@ func (q *Queries) ListParentsWithoutSystemWakeup(ctx context.Context, arg ListPa
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/wakeup.sql.go b/server/pkg/db/generated/wakeup.sql.go
index 46ad210679..0edc957d96 100644
--- a/server/pkg/db/generated/wakeup.sql.go
+++ b/server/pkg/db/generated/wakeup.sql.go
@@ -1518,7 +1518,7 @@ func (q *Queries) LockIssueWakeup(ctx context.Context, id pgtype.UUID) (IssueWak
}
const lockWakeupIssue = `-- name: LockWakeupIssue :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id FROM issue WHERE id= $1 FOR NO KEY UPDATE
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id, requester_user_id, description_revision FROM issue WHERE id= $1 FOR NO KEY UPDATE
`
func (q *Queries) LockWakeupIssue(ctx context.Context, id pgtype.UUID) (Issue, error) {
@@ -1556,6 +1556,7 @@ func (q *Queries) LockWakeupIssue(ctx context.Context, id pgtype.UUID) (Issue, e
&i.TriageState,
&i.DuplicateOfIssueID,
&i.RequesterUserID,
+ &i.DescriptionRevision,
)
return i, err
}
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 823bc77edc..ae98f75ff7 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -277,6 +277,12 @@ deleted_child_events AS (
deleted_unread AS (
DELETE FROM issue_unread WHERE workspace_id=$1
),
+deleted_description_collab_state AS (
+ DELETE FROM issue_description_collab_state WHERE workspace_id=$1
+),
+deleted_description_revisions AS (
+ DELETE FROM issue_description_revision WHERE workspace_id=$1
+),
deleted_issues AS (
DELETE FROM issue WHERE issue.workspace_id = $1
),
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index db58ab2a4e..abab4eb66c 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -135,6 +135,7 @@ SET description = CASE
ELSE description || E'\n\n' || sqlc.arg(markdown)
END,
revision = revision + 1,
+ description_revision = description_revision + 1,
updated_at = now()
WHERE id = sqlc.arg(id)
AND workspace_id = sqlc.arg(workspace_id)
@@ -282,6 +283,8 @@ UPDATE issue AS i SET
stage = changed.next_stage,
duplicate_of_issue_id = changed.next_duplicate_of_issue_id,
revision = i.revision + changed.did_change::integer,
+ description_revision = i.description_revision
+ + (changed.next_description IS DISTINCT FROM changed.description)::integer,
last_activity_at = CASE WHEN changed.did_activity
THEN GREATEST(COALESCE(i.last_activity_at, i.updated_at), now())
ELSE i.last_activity_at
@@ -502,6 +505,12 @@ cleared_environment_configs AS (
-- so their receipts are swept here by the issue_id copied onto each row.
cleared_task_context_receipts AS (
DELETE FROM task_context_receipt WHERE issue_id IN (SELECT target.id FROM target)
+),
+cleared_description_collab_state AS (
+ DELETE FROM issue_description_collab_state WHERE issue_id IN (SELECT target.id FROM target)
+),
+cleared_description_revisions AS (
+ DELETE FROM issue_description_revision WHERE issue_id IN (SELECT target.id FROM target)
)
DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target);
diff --git a/server/pkg/db/queries/issue_description_collab.sql b/server/pkg/db/queries/issue_description_collab.sql
new file mode 100644
index 0000000000..0862f4b813
--- /dev/null
+++ b/server/pkg/db/queries/issue_description_collab.sql
@@ -0,0 +1,59 @@
+-- name: GetIssueDescriptionForCollab :one
+-- The collaboration service's view of a description: the stored text plus the
+-- Yjs state last saved with it, which is only reusable at the same revision.
+SELECT i.workspace_id, i.description, i.description_revision,
+ s.ystate AS ystate, s.revision AS ystate_revision
+FROM issue i
+LEFT JOIN issue_description_collab_state s ON s.issue_id = i.id
+WHERE i.id = $1;
+
+-- name: LockIssueByIDForUpdate :one
+SELECT * FROM issue WHERE id = $1 FOR UPDATE;
+
+-- name: UpsertIssueDescriptionCollabState :exec
+INSERT INTO issue_description_collab_state (issue_id, workspace_id, ystate, revision)
+VALUES (@issue_id, @workspace_id, @ystate, @revision)
+ON CONFLICT (issue_id) DO UPDATE SET
+ ystate = EXCLUDED.ystate,
+ revision = EXCLUDED.revision,
+ updated_at = now();
+
+-- name: InsertIssueDescriptionRevision :exec
+INSERT INTO issue_description_revision (issue_id, workspace_id, revision, content)
+VALUES (@issue_id, @workspace_id, @revision, @content)
+ON CONFLICT (issue_id, revision) DO UPDATE SET content = EXCLUDED.content;
+
+-- name: PruneIssueDescriptionRevisions :exec
+DELETE FROM issue_description_revision
+WHERE issue_id = @issue_id AND revision < @keep_from;
+
+-- name: GetIssueDescriptionRevisionContent :one
+SELECT content FROM issue_description_revision
+WHERE issue_id = @issue_id AND revision = @revision;
+
+-- name: HasRecentLiveDescriptionActivity :one
+-- A live editing session records one description_updated entry per editor:
+-- saves within 30 minutes of that editor's last live entry add none.
+SELECT EXISTS (
+ SELECT 1 FROM activity_log
+ WHERE issue_id = @issue_id
+ AND action = 'description_updated'
+ AND actor_type = @actor_type
+ AND actor_id = @actor_id
+ AND details->>'live' = 'true'
+ AND created_at > now() - interval '30 minutes'
+);
+
+-- name: LinkUnboundAttachmentsToIssue :execrows
+-- Binds files uploaded into a live description to its issue, as the solo
+-- editor does with attachment_ids on save. Only files one of the editors
+-- uploaded and nothing owns yet.
+UPDATE attachment SET issue_id = @issue_id
+WHERE workspace_id = @workspace_id
+ AND id = ANY(@attachment_ids::uuid[])
+ AND issue_id IS NULL
+ AND comment_id IS NULL
+ AND chat_session_id IS NULL
+ AND chat_message_id IS NULL
+ AND source_context_id IS NULL
+ AND uploader_id = ANY(@uploader_ids::uuid[]);
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 2966cbc5df..93aa0855c7 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -617,6 +617,12 @@ deleted_child_events AS (
deleted_unread AS (
DELETE FROM issue_unread WHERE workspace_id=$1
),
+deleted_description_collab_state AS (
+ DELETE FROM issue_description_collab_state WHERE workspace_id=$1
+),
+deleted_description_revisions AS (
+ DELETE FROM issue_description_revision WHERE workspace_id=$1
+),
deleted_issues AS (
DELETE FROM issue WHERE issue.workspace_id = $1
),