Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: promote finished sprint text to draft (#5300)

[._.]/ Adam Eivyeaab0bd051a7
diff --git a/client/src/components/writers-room/ExercisePanel.jsx b/client/src/components/writers-room/ExercisePanel.jsx
index 6a12067913..0486aa44f6 100644
--- a/client/src/components/writers-room/ExercisePanel.jsx
+++ b/client/src/components/writers-room/ExercisePanel.jsx
@@ -1,11 +1,12 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { Timer, Play, StopCircle, X } from 'lucide-react';
+import { Timer, Play, StopCircle, X, FilePlus } from 'lucide-react';
import toast from '../ui/Toast';
import {
listWritersRoomExercises,
createWritersRoomExercise,
finishWritersRoomExercise,
discardWritersRoomExercise,
+ promoteWritersRoomExercise,
} from '../../services/apiWritersRoom';
import { countWords, formatCountdown } from '../../utils/formatters';
import { FormField } from '../ui/FormField';
@@ -18,7 +19,7 @@ const DURATION_PRESETS = [
{ label: '25 min', seconds: 1500 },
];
-export default function ExercisePanel({ activeWork, onClose }) {
+export default function ExercisePanel({ activeWork, onClose, editorDirty = false, onWorkChange }) {
const [history, setHistory] = useState([]);
const [duration, setDuration] = useState(600);
const [prompt, setPrompt] = useState('');
@@ -103,6 +104,17 @@ export default function ExercisePanel({ activeWork, onClose }) {
await refresh();
};
+ const promote = async (exercise) => {
+ const result = await promoteWritersRoomExercise(exercise.id, { silent: true }).catch((err) => {
+ toast.error(`Could not add to draft: ${err.message}`);
+ return null;
+ });
+ if (!result) return;
+ toast.success(`Added ${countWords(exercise.appendedText)} words to draft`);
+ onWorkChange?.(result.work);
+ await refresh();
+ };
+
// Toast once when the timer crosses into expired. The ref guards against
// multiple fires if `expired` stays true across re-renders.
const expiredToastedRef = useRef(false);
@@ -216,6 +228,18 @@ export default function ExercisePanel({ activeWork, onClose }) {
</span>
<span className="text-gray-600 truncate flex-1">{ex.prompt || '(free-write)'}</span>
<span className="text-gray-600">{Math.round((ex.durationSeconds || 0) / 60)}m</span>
+ {ex.promotedAt && <span className="text-port-success">✓ in draft</span>}
+ {ex.status === 'finished' && ex.appendedText && ex.workId === activeWork?.id && !ex.promotedAt && (
+ <button
+ onClick={() => promote(ex)}
+ disabled={editorDirty}
+ title={editorDirty ? 'Save first' : 'Add to draft'}
+ aria-label="Add sprint text to draft"
+ className="min-h-[44px] min-w-[44px] flex items-center justify-center text-port-accent disabled:text-gray-600"
+ >
+ <FilePlus size={15} />
+ </button>
+ )}
</li>
))}
</ul>
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index 85ae2c428f..5e9ae335eb 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -102,7 +102,7 @@ function readSidebarTab() {
return STORYBOARD_TAB_VALUES.includes(stored) ? stored : STORYBOARD_TAB.BOARDS;
}
-export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOpen }) {
+export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOpen, onDirtyChange }) {
const navigate = useNavigate();
const [body, setBody] = useState(work.activeDraftBody || '');
const [title, setTitle] = useState(work.title);
@@ -254,14 +254,16 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
// Rehydrate body/title when the parent swaps the active work OR switches to
// a different draft version of the same work.
const prevKey = useRef({ id: work.id, draftId: work.activeDraftVersionId });
+ const dirty = body !== savedBody;
useEffect(() => {
const key = { id: work.id, draftId: work.activeDraftVersionId };
- if (prevKey.current.id === key.id && prevKey.current.draftId === key.draftId) return;
+ const hasNewCleanBody = work.activeDraftBody !== savedBody && !dirty;
+ if (prevKey.current.id === key.id && prevKey.current.draftId === key.draftId && !hasNewCleanBody) return;
prevKey.current = key;
setBody(work.activeDraftBody || '');
setSavedBody(work.activeDraftBody || '');
setTitle(work.title);
- }, [work.id, work.activeDraftVersionId, work.activeDraftBody, work.title]);
+ }, [work.id, work.activeDraftVersionId, work.activeDraftBody, work.title, savedBody, dirty]);
useEffect(() => { setStatus(work.status); }, [work.status]);
useEffect(() => { setTitle(work.title); }, [work.title]);
@@ -281,7 +283,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
});
}, [work.id]);
- const dirty = body !== savedBody;
+ useEffect(() => { onDirtyChange?.(dirty); }, [dirty, onDirtyChange]);
const wordCount = useMemo(() => countWords(body), [body]);
// Live mirror of `body` for callbacks that only READ the prose (#3387).
diff --git a/client/src/pages/WritersRoom.jsx b/client/src/pages/WritersRoom.jsx
index 7d1f79417f..49330db078 100644
--- a/client/src/pages/WritersRoom.jsx
+++ b/client/src/pages/WritersRoom.jsx
@@ -23,6 +23,7 @@ export default function WritersRoom() {
const [activeWork, setActiveWork] = useState(null);
const [loadingWork, setLoadingWork] = useState(false);
const [showExercise, setShowExercise] = useState(false);
+ const [editorDirty, setEditorDirty] = useState(false);
// Header + library collapse state. Opening a work auto-collapses both (see
// selectWork) so the editor gets maximum room — this now applies on mobile
// too, where the library is an inline block stacked above the editor. The
@@ -211,6 +212,7 @@ export default function WritersRoom() {
onChange={handleWorkChange}
onToggleExercise={() => setShowExercise((s) => !s)}
exerciseOpen={showExercise}
+ onDirtyChange={setEditorDirty}
/>
</>
)}
@@ -218,7 +220,7 @@ export default function WritersRoom() {
{showExercise && (
<aside className="border-t lg:border-t-0 lg:border-l border-port-border bg-port-card/30 p-3 min-h-0 lg:overflow-y-auto">
- <ExercisePanel activeWork={activeWork} onClose={() => setShowExercise(false)} />
+ <ExercisePanel activeWork={activeWork} editorDirty={editorDirty} onWorkChange={handleWorkChange} onClose={() => setShowExercise(false)} />
</aside>
)}
</div>
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index 8af290dbb5..bc6407ec00 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -242,3 +242,7 @@ export const discardWritersRoomExercise = (id, options = {}) => request(`/writer
method: 'POST',
...options,
});
+export const promoteWritersRoomExercise = (id, options = {}) => request(`/writers-room/exercises/${enc(id)}/promote`, {
+ method: 'POST',
+ ...options,
+});
diff --git a/docs/features/writers-room.md b/docs/features/writers-room.md
index 6763171d95..6e2161a16e 100644
--- a/docs/features/writers-room.md
+++ b/docs/features/writers-room.md
@@ -16,9 +16,9 @@ The page lives in the sidebar's **Create** group. The main workspace is `client/
## Writing Exercise ("write for 10")
-`ExercisePanel.jsx` runs timed free-write sprints (default 10 minutes, clamped 1–60): start, finish, or discard, with live word count. Sessions can start standalone or attached to a work, and history records date, duration, word deltas, linked work, and prompt. Finished sprint text is stored as `appendedText` on the exercise record.
+`ExercisePanel.jsx` runs timed free-write sprints (default 10 minutes, clamped 1–60): start, finish, or discard, with live word count. Sessions can start standalone or attached to a work, and history records date, duration, word deltas, linked work, and prompt. Finished sprint text is stored as `appendedText` on the exercise record. A finished sprint tied to the open work can be added to its active draft; promotion appends the trimmed sprint text, records `promotedAt` and `promotedDraftVersionId`, and keeps the existing draft version and ingredient references.
-Not built (deliberately deferred): pause/resume mid-session, and a "promote to draft" action that merges `appendedText` into the work — the session record carries everything needed to add it later.
+Not built (deliberately deferred): pause/resume mid-session.
## Storage
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 78796676ee..d68f517cca 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -22253,6 +22253,17 @@
}
]
},
+ {
+ "method": "POST",
+ "path": "/api/writers-room/exercises/:id/promote",
+ "mountPath": "/api/writers-room",
+ "sources": [
+ {
+ "source": "server/routes/writersRoom.js",
+ "line": 196
+ }
+ ]
+ },
{
"method": "GET",
"path": "/api/writers-room/folders",
@@ -22348,7 +22359,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 198
+ "line": 202
}
]
},
@@ -22359,7 +22370,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 202
+ "line": 206
}
]
},
@@ -22370,7 +22381,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 208
+ "line": 212
}
]
},
@@ -22381,7 +22392,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 370
+ "line": 374
}
]
},
@@ -22392,7 +22403,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 290
+ "line": 294
}
]
},
@@ -22403,7 +22414,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 281
+ "line": 285
}
]
},
@@ -22414,7 +22425,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 306
+ "line": 310
}
]
},
@@ -22425,7 +22436,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 310
+ "line": 314
}
]
},
@@ -22436,7 +22447,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 320
+ "line": 324
}
]
},
@@ -22447,7 +22458,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 315
+ "line": 319
}
]
},
@@ -22469,7 +22480,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 271
+ "line": 275
}
]
},
@@ -22480,7 +22491,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 262
+ "line": 266
}
]
},
@@ -22491,7 +22502,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 346
+ "line": 350
}
]
},
@@ -22502,7 +22513,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 350
+ "line": 354
}
]
},
@@ -22513,7 +22524,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 360
+ "line": 364
}
]
},
@@ -22524,7 +22535,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 355
+ "line": 359
}
]
},
@@ -22535,7 +22546,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 326
+ "line": 330
}
]
},
@@ -22546,7 +22557,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 330
+ "line": 334
}
]
},
@@ -22557,7 +22568,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 340
+ "line": 344
}
]
},
@@ -22568,7 +22579,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 335
+ "line": 339
}
]
},
@@ -22579,7 +22590,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 235
+ "line": 239
}
]
},
@@ -22590,7 +22601,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 228
+ "line": 232
}
]
},
@@ -22601,7 +22612,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 251
+ "line": 255
}
]
},
@@ -22612,7 +22623,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 243
+ "line": 247
}
]
},
@@ -22623,7 +22634,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 247
+ "line": 251
}
]
},
@@ -22634,7 +22645,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 218
+ "line": 222
}
]
},
@@ -22645,7 +22656,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 239
+ "line": 243
}
]
},
@@ -22667,7 +22678,7 @@
"sources": [
{
"source": "server/routes/writersRoom.js",
- "line": 300
+ "line": 304
}
]
},
@@ -22960,8 +22971,8 @@
],
"stats": {
"mounts": 145,
- "operations": 2071,
- "declarations": 2074,
+ "operations": 2072,
+ "declarations": 2075,
"sourceFiles": 224
}
}
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index d3204ac13e..06c15b60db 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -35,7 +35,7 @@ import {
listFolders, createFolder, deleteFolder,
listWorks, getWorkWithBody, createWork, updateWork, deleteWork,
saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,
- listExercises, createExercise, finishExercise, discardExercise,
+ listExercises, createExercise, finishExercise, discardExercise, promoteExercise,
} from '../services/writersRoom/local.js';
import {
runAnalysis, listAnalyses, getAnalysis, persistSceneImage,
@@ -193,6 +193,10 @@ router.post('/exercises/:id/discard', asyncHandler(async (req, res) => {
res.json(await discardExercise(req.params.id));
}));
+router.post('/exercises/:id/promote', asyncHandler(async (req, res) => {
+ res.json(await promoteExercise(req.params.id));
+}));
+
// ---------- analysis ----------
router.get('/works/:id/analysis', asyncHandler(async (req, res) => {
diff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.js
index 61508a1676..6ab08e5d50 100644
--- a/server/routes/writersRoom.test.js
+++ b/server/routes/writersRoom.test.js
@@ -20,6 +20,7 @@ vi.mock('../services/writersRoom/local.js', () => ({
createExercise: vi.fn(async (data) => ({ id: 'wr-ex-new', ...data })),
finishExercise: vi.fn(async (id) => ({ id, status: 'finished' })),
discardExercise: vi.fn(async (id) => ({ id, status: 'discarded' })),
+ promoteExercise: vi.fn(async (id) => ({ exercise: { id, promotedAt: '2026-01-01T00:00:00.000Z' }, work: { id: 'wr-work-1' } })),
ensureWorkMediaCollection: vi.fn(async () => ({ id: 'col-1' })),
}));
@@ -264,6 +265,12 @@ describe('writersRoom routes', () => {
expect(r.status).toBe(200);
expect(svc.discardExercise).toHaveBeenCalledWith('wr-ex-1');
});
+
+ it('POST /exercises/:id/promote hits the promotion handler', async () => {
+ const r = await request(app).post('/api/writers-room/exercises/wr-ex-1/promote');
+ expect(r.status).toBe(200);
+ expect(svc.promoteExercise).toHaveBeenCalledWith('wr-ex-1');
+ });
});
describe('characters', () => {
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 958d58cc62..797110a58c 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -688,6 +688,30 @@ export async function finishExercise(id, { endingWords, appendedText = null } =
return finished;
}
+export async function promoteExercise(id) {
+ const all = await store().listExercises();
+ const existing = all.find((exercise) => exercise.id === id);
+ if (!existing) throw notFound('Exercise');
+ if (existing.promotedAt) throw badRequest('Exercise already promoted');
+ if (existing.status !== 'finished') throw badRequest('Exercise must be finished before promotion');
+ if (!existing.workId) throw badRequest('Exercise is not linked to a work');
+ const text = typeof existing.appendedText === 'string' ? existing.appendedText.trim() : '';
+ if (!text) throw badRequest('Exercise has no text to promote');
+
+ const { manifest, body } = await getWorkWithBody(existing.workId);
+ const nextBody = body.trimEnd() === '' ? text : `${body.trimEnd()}\n\n${text}\n`;
+ const { manifest: updatedManifest } = await saveDraftBody(existing.workId, nextBody);
+ const promoted = {
+ ...existing,
+ promotedAt: nowIso(),
+ promotedDraftVersionId: updatedManifest.activeDraftVersionId,
+ updatedAt: nowIso(),
+ };
+ await store().writeExercise(promoted);
+ emitRecordUpdated(WRITERS_ROOM_EXERCISE_KIND, id);
+ return { exercise: promoted, work: { ...updatedManifest, activeDraftBody: nextBody } };
+}
+
export async function discardExercise(id) {
const all = await store().listExercises();
const existing = all.find((e) => e.id === id);
@@ -701,7 +725,7 @@ export async function discardExercise(id) {
}
// Conflict-restore for an exercise sprint — see restoreBodylessRecord above.
-const EXERCISE_RESTORABLE = ['workId', 'prompt', 'durationSeconds', 'startingWords', 'endingWords', 'wordsAdded', 'appendedText', 'status', 'finishedAt'];
+const EXERCISE_RESTORABLE = ['workId', 'prompt', 'durationSeconds', 'startingWords', 'endingWords', 'wordsAdded', 'appendedText', 'status', 'finishedAt', 'promotedAt', 'promotedDraftVersionId'];
export async function restoreExercise(id, patch) {
return restoreBodylessRecord(id, patch, {
read: (rid, opts) => store().readExercise(rid, opts),
diff --git a/server/services/writersRoom/local.test.js b/server/services/writersRoom/local.test.js
index f9e4a93af1..050a1e8f03 100644
--- a/server/services/writersRoom/local.test.js
+++ b/server/services/writersRoom/local.test.js
@@ -17,7 +17,7 @@ const {
listFolders, createFolder, deleteFolder,
listWorks, countWorks, createWork, getWork, getWorkWithBody, updateWork, deleteWork,
saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,
- listExercises, createExercise, finishExercise, discardExercise,
+ listExercises, createExercise, finishExercise, discardExercise, promoteExercise,
resolveLiveMode, recordLiveModeUsage, recordLiveModeRenderUsage, DEFAULT_LIVE_MODE,
renderWorkVoiceGuide,
} = local;
@@ -388,6 +388,36 @@ describe('exercise sessions', () => {
expect(finished2.endingWords).toBe(200);
});
+ it('promoteExercise appends trimmed sprint text and preserves the active draft references', async () => {
+ const work = await createWork({ title: 'Promotion' });
+ await saveDraftBody(work.id, 'Existing draft', { referencedIngredientIds: ['cat-char-1'] });
+ const exercise = await createExercise({ workId: work.id });
+ await finishExercise(exercise.id, { appendedText: ' Sprint ending ' });
+
+ const result = await promoteExercise(exercise.id);
+ expect(result.work.activeDraftBody).toBe('Existing draft\n\nSprint ending\n');
+ expect(result.work.drafts[0].wordCount).toBe(4);
+ expect(result.work.drafts[0].referencedIngredientIds).toEqual(['cat-char-1']);
+ expect(result.exercise.promotedAt).toBeTruthy();
+ expect(result.exercise.promotedDraftVersionId).toBe(work.activeDraftVersionId);
+ await expect(promoteExercise(exercise.id)).rejects.toThrow(/already promoted/i);
+ });
+
+ it('promoteExercise rejects unfinished, standalone, and empty exercises', async () => {
+ const work = await createWork({ title: 'Promotion guards' });
+ const running = await createExercise({ workId: work.id });
+ await expect(promoteExercise(running.id)).rejects.toThrow(/finished/i);
+
+ const standalone = await createExercise({});
+ await finishExercise(standalone.id, { appendedText: 'Text' });
+ await expect(promoteExercise(standalone.id)).rejects.toThrow(/linked/i);
+
+ const empty = await createExercise({ workId: work.id });
+ await finishExercise(empty.id, { appendedText: ' ' });
+ await expect(promoteExercise(empty.id)).rejects.toThrow(/no text/i);
+ await expect(promoteExercise('wr-ex-missing')).rejects.toThrow(/not found/i);
+ });
+
it('discardExercise marks the session as discarded', async () => {
const ex = await createExercise({});
const discarded = await discardExercise(ex.id);