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

refactor: fold D&D avatar persistence into POST /image-gen/avatar (#1364)

Adam Eivy3b685798a0c5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 06ad7701a2..3c7b1e88d3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -75,6 +75,8 @@
## Changed
+- **[issue-1364] Generating a D&D character avatar now persists in one round-trip.** The character-sheet "Generate avatar" flow used to render the image and then make a *second* call to save the path onto your character. Since the avatar route already knows the character context, it now persists the rendered `avatarPath` itself when asked (`persistToCharacter`), so the client drops the follow-up `PUT /api/character` and keeps its optimistic update — same result, one fewer request. (`server/routes/imageGen.js`, `server/services/character.js`, `client/src/pages/CharacterSheet.jsx`, #1364)
+
- **[issue-1291] The character-name confusability check now catches look-alikes *and* sound-alikes, reads aliases, and respects locked characters.** The "Character name dissimilarity" editorial check used to compare only spelling traits — shared first letter, length, vowel pattern, opening, or ending. It now also flags names that are a near-typo apart (edit distance, e.g. *Alina* / *Alana*) or that simply *sound alike* (a phonetic match, e.g. *Smith* / *Smyth*, *Sam* / *Sun*), compares each character's **aliases** as well as their primary name, and adds a **first-letter crowding** finding when too much of the cast starts with the same letter (scaled to cast size — two M-names in a cast of thirty is fine, four of six is not). Severity now scales with how confusable a pair really is, near-identical names rank highest, and every suggestion steers you to rename an **unlocked** character (and tells you when both are locked). New per-check knobs let you tune the edit-distance threshold, the crowding ratio, and toggle the length/vowel/phonetic signals individually. (#1291)
- **[issue-1387] Editorial-check "stale" badges are now scoped to exactly what each check reads, so a single edit no longer marks unrelated findings stale.** A finding's stale badge tells you the manuscript/canon/series content the check analyzed has drifted since it ran. That signal used to be derived from a coarse two-bucket heuristic (manuscript-vs-canon) that folded the *style guide* and the *arc ticking clock* into shared buckets — so editing the ticking clock marked **every** canon-only finding stale (naming, object-attachment, …), and editing the style guide marked **every** manuscript finding stale (even the info-dumping check, which never reads the style guide). Each check now declares the exact inputs it reads (`sources`, a subset of `manuscript` / `canon` / `series.styleGuide` / `series.arc.tickingClock`) and the runner fingerprints precisely those — so editing the ticking clock stales only the ticking-clock-hygiene finding, editing the style guide stales only the style checks, and a future check that reads a new series field can't silently stay falsely "fresh" (a fail-fast guard requires every check to declare a non-empty, known source set, and a `manuscript` source to pair with `needsManuscript`). A custom check's authored prompt is folded into its fingerprint too, so editing what a custom check looks for stales its prior findings even when the manuscript hasn't changed. Staleness is still derived per-read and never stored or synced. (`server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, #1387)
diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsx
index 40490b9be0..f91d6f2c6f 100644
--- a/client/src/pages/CharacterSheet.jsx
+++ b/client/src/pages/CharacterSheet.jsx
@@ -213,10 +213,12 @@ export default function CharacterSheet() {
setDiffusionProgress(null);
generatingRef.current = true;
generationIdRef.current = null;
- generateAvatar({ name: char.name, characterClass: char.class })
+ // The route persists `avatarPath` onto the character server-side
+ // (persistToCharacter), so no follow-up charPut is needed — keep the
+ // optimistic setChar for instant feedback.
+ generateAvatar({ name: char.name, characterClass: char.class, persistToCharacter: true })
.then(result => {
setChar(prev => ({ ...prev, avatarPath: result.path }));
- return charPut({ avatarPath: result.path });
})
.catch(err => toast.error(err.message || 'Failed to generate avatar'))
.finally(() => {
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index e4694fa30b..e6a7ff1727 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -44,6 +44,7 @@ import {
} from '../services/imageGen/regen.js';
import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';
import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';
+import * as characterService from '../services/character.js';
import { randomUUID } from 'crypto';
const router = Router();
@@ -223,6 +224,10 @@ const avatarSchema = z.object({
name: z.string().max(100).optional(),
characterClass: z.string().max(100).optional(),
prompt: z.string().max(2000).optional(),
+ // When set, the route persists the rendered path onto the singleton
+ // character record itself (the character store has no id), so the client
+ // skips the follow-up PUT /api/character round-trip.
+ persistToCharacter: z.boolean().optional(),
});
// Upload a user-supplied image straight into the gallery (`data/images/`) so it
@@ -441,7 +446,14 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
router.post('/avatar', asyncHandler(async (req, res) => {
const data = validateRequest(avatarSchema, req.body);
- res.json(await imageGen.generateAvatar(data));
+ const result = await imageGen.generateAvatar(data);
+ // `result.path` is server-generated as `/data/images/<file>` (the same value
+ // the client previously round-tripped through PUT /api/character), so it's
+ // safe to persist directly without re-validating against the path regex.
+ if (data.persistToCharacter && result?.path) {
+ await characterService.setAvatar(result.path);
+ }
+ res.json(result);
}));
// Save an uploaded image into the gallery dir so callers (e.g. author
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index b261302d47..8e94fd4ffd 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -59,6 +59,13 @@ vi.mock('../services/mediaCollections.js', () => ({
findOrCreateUniverseCollection: vi.fn(async ({ universeId }) => ({ id: `col-${universeId}` })),
}));
+// POST /avatar folds character-avatar persistence in when persistToCharacter is
+// set. Mock the service so the test asserts the wiring without touching the
+// real singleton character store.
+vi.mock('../services/character.js', () => ({
+ setAvatar: vi.fn(async (avatarPath) => ({ name: 'Gandalf', avatarPath })),
+}));
+
// HOST_ARCH is read at request time inside `buildSetupCheck`, so backing it
// with a hoisted mutable holder + getter lets tests flip between arm64 and
// x86_64 hosts without re-mocking. Default arm64 keeps every existing test
@@ -93,6 +100,7 @@ vi.mock('fs/promises', async (importOriginal) => {
});
import * as imageGen from '../services/imageGen/index.js';
+import * as characterService from '../services/character.js';
import * as mediaJobQueue from '../services/mediaJobQueue/index.js';
import { getSettings } from '../services/settings.js';
import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';
@@ -741,6 +749,37 @@ describe('Image Gen Routes', () => {
expect(response.body.filename).toBe('default.png');
expect(response.body.path).toBe('/data/images/default.png');
});
+
+ it('persists the rendered path onto the character when persistToCharacter is set', async () => {
+ imageGen.generateAvatar.mockResolvedValue({
+ generationId: 'gen-005',
+ filename: 'avatar.png',
+ path: '/data/images/avatar.png',
+ });
+
+ const response = await request(app)
+ .post('/api/image-gen/avatar')
+ .send({ name: 'Gandalf', characterClass: 'Wizard', persistToCharacter: true });
+
+ expect(response.status).toBe(200);
+ expect(response.body.path).toBe('/data/images/avatar.png');
+ expect(characterService.setAvatar).toHaveBeenCalledWith('/data/images/avatar.png');
+ });
+
+ it('does NOT persist to the character when persistToCharacter is omitted', async () => {
+ imageGen.generateAvatar.mockResolvedValue({
+ generationId: 'gen-006',
+ filename: 'avatar.png',
+ path: '/data/images/avatar.png',
+ });
+
+ const response = await request(app)
+ .post('/api/image-gen/avatar')
+ .send({ name: 'Gandalf', characterClass: 'Wizard' });
+
+ expect(response.status).toBe(200);
+ expect(characterService.setAvatar).not.toHaveBeenCalled();
+ });
});
describe('POST /api/image-gen/upload', () => {
diff --git a/server/services/character.js b/server/services/character.js
index 269ac9483d..934df766c1 100644
--- a/server/services/character.js
+++ b/server/services/character.js
@@ -90,6 +90,17 @@ export async function saveCharacter(data) {
return data;
}
+// Persist a freshly-rendered avatar path onto the singleton character. Lets the
+// avatar-generation route fold persistence in (it already knows the character
+// context) instead of forcing a second `PUT /api/character` round-trip.
+export async function setAvatar(avatarPath) {
+ const character = await getCharacter();
+ character.avatarPath = avatarPath;
+ await saveCharacter(character);
+ console.log(`🖼️ Character avatar set → ${avatarPath}`);
+ return character;
+}
+
export function rollDice(notation) {
const match = notation.match(/^(\d+)d(\d+)([+-]\d+)?$/);
if (!match) throw new Error(`Invalid dice notation: ${notation}`);
diff --git a/server/services/character.test.js b/server/services/character.test.js
new file mode 100644
index 0000000000..46827710f1
--- /dev/null
+++ b/server/services/character.test.js
@@ -0,0 +1,42 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// In-memory backing for the character.json read/write so the test exercises the
+// real read-modify-save path without touching disk.
+const store = vi.hoisted(() => ({ value: null }));
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { data: '/tmp/portos-test-data' },
+ ensureDir: vi.fn(async () => {}),
+ readJSONFile: vi.fn(async (_file, fallback) => (store.value ?? fallback)),
+ writeFile: vi.fn(),
+}));
+
+// character.js eagerly imports the jira/cos services at module load; stub them
+// so the unit under test loads without their dependency graphs.
+vi.mock('./jira.js', () => ({}));
+vi.mock('./cos.js', () => ({}));
+
+vi.mock('fs/promises', () => ({
+ writeFile: vi.fn(async (_path, contents) => {
+ store.value = JSON.parse(contents);
+ }),
+}));
+
+import * as characterService from './character.js';
+
+describe('character setAvatar', () => {
+ beforeEach(() => {
+ store.value = { name: 'Gandalf', class: 'Wizard', avatarPath: null, xp: 0, level: 1 };
+ });
+
+ it('persists avatarPath onto the existing character and returns it', async () => {
+ const updated = await characterService.setAvatar('/data/images/avatar.png');
+
+ expect(updated.avatarPath).toBe('/data/images/avatar.png');
+ // Other fields are preserved (read-modify-save, not a replace).
+ expect(updated.name).toBe('Gandalf');
+ expect(updated.class).toBe('Wizard');
+ // And it was actually persisted.
+ expect(store.value.avatarPath).toBe('/data/images/avatar.png');
+ });
+});