1
0
Fork 0

Compare commits

..

No commits in common. "e39de39e35b00b368e37298ca016c79443e0672d" and "97f88a24b9c39b1557803a2b292310d1c94bb374" have entirely different histories.

5 changed files with 164 additions and 309 deletions

View File

@ -65,10 +65,10 @@ export const highlight = (message: string, keepMarkup = true): string => {
} else if (token === '```') {
stack.push(token);
inCodeBlock = true;
resultHTML += `<span class="${styles.codeBlock}">${keepToken ? token : ''}`;
resultHTML += `<span class="${styles.codeBlock}">`;
} else if (token === '`') {
stack.push(token);
resultHTML += `<span class="${styles.inlineCode}">${keepToken ? token : ''}`;
resultHTML += `<span class="${styles.inlineCode}">`;
}
}

View File

@ -20,26 +20,27 @@ const TABS: { id: Tab; label: string }[] = [
export const Editor = () => {
const { currentStory, dispatch } = useAppState();
if (!currentStory) {
return <div class={styles.editor} />;
}
const handleInput = useInputCallback((text: string) => {
if (!currentStory) return;
dispatch({
type: 'EDIT_STORY',
id: currentStory.id,
text,
});
}, [currentStory?.id]);
}, []);
const handleLoreInput = useInputCallback((lore: string) => {
if (!currentStory) return;
dispatch({
type: 'EDIT_LORE',
id: currentStory.id,
lore,
});
}, [currentStory?.id]);
}, []);
const handleTabChange = (tab: Tab) => {
if (!currentStory) return;
dispatch({
type: 'SET_CURRENT_TAB',
id: currentStory.id,
@ -47,12 +48,8 @@ export const Editor = () => {
});
};
const storyValue = useMemo(() => currentStory ? highlight(currentStory.text) : '', [currentStory?.text]);
const loreValue = useMemo(() => currentStory ? highlight(currentStory.lore) : '', [currentStory?.lore]);
if (!currentStory) {
return <div class={styles.editor} />;
}
const storyValue = useMemo(() => highlight(currentStory.text), [currentStory.text]);
const loreValue = useMemo(() => highlight(currentStory.lore), [currentStory.lore]);
return (
<div class={styles.editor}>

View File

@ -4,10 +4,10 @@ import { ConnectionSettingsModal } from "./connection-settings-modal";
import { SettingsModal } from "./settings-modal";
import { useAppState } from "../contexts/state";
import { useBool } from "@common/hooks/useBool";
import { useInputState } from "@common/hooks/useInputState";
import type { Story } from "../contexts/state";
import styles from '../assets/menu-sidebar.module.css';
import { Pencil, X, Plus, Plug, Settings, Copy } from "lucide-preact";
import { useState } from "preact/hooks";
import { Pencil, X, Plus, Plug, Settings } from "lucide-preact";
// ─── Story Item ───────────────────────────────────────────────────────────────
@ -17,18 +17,17 @@ interface StoryItemProps {
onSelect: () => void;
onRename: (newTitle: string) => void;
onDelete: () => void;
onDuplicate: () => void;
}
const StoryItem = ({ story, active, onSelect, onRename, onDelete, onDuplicate }: StoryItemProps) => {
const isEditing = useBool(false);
const [editTitle, setEditTitle] = useInputState(story.title);
const StoryItem = ({ story, active, onSelect, onRename, onDelete }: StoryItemProps) => {
const [isEditing, setIsEditing] = useState(false);
const [editTitle, setEditTitle] = useState(story.title);
const handleSubmit = () => {
if (editTitle.trim()) {
onRename(editTitle.trim());
}
isEditing.setFalse();
setIsEditing(false);
};
const handleKeyDown = (e: KeyboardEvent) => {
@ -36,7 +35,7 @@ const StoryItem = ({ story, active, onSelect, onRename, onDelete, onDuplicate }:
handleSubmit();
} else if (e.key === 'Escape') {
setEditTitle(story.title);
isEditing.setFalse();
setIsEditing(false);
}
};
@ -44,13 +43,13 @@ const StoryItem = ({ story, active, onSelect, onRename, onDelete, onDuplicate }:
handleSubmit();
};
if (isEditing.value) {
if (isEditing) {
return (
<div class={clsx(styles.itemWrapper, active && styles.active)}>
<input
class={styles.input}
value={editTitle}
onInput={setEditTitle}
onInput={(e) => setEditTitle((e.target as HTMLInputElement).value)}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
autoFocus
@ -64,17 +63,13 @@ const StoryItem = ({ story, active, onSelect, onRename, onDelete, onDuplicate }:
<button
class={clsx(styles.item, active && styles.active)}
onClick={onSelect}
onDblClick={isEditing.setTrue}
>
{story.title}
</button>
<div class={styles.actions}>
<button class={styles.actionButton} onClick={isEditing.setTrue} title="Rename">
<button class={styles.actionButton} onClick={() => setIsEditing(true)} title="Rename">
<Pencil size={14} />
</button>
<button class={styles.actionButton} onClick={onDuplicate} title="Duplicate">
<Copy size={14} />
</button>
<button class={styles.actionButton} onClick={onDelete} title="Delete">
<X size={14} />
</button>
@ -110,10 +105,6 @@ export const MenuSidebar = () => {
}
};
const handleDuplicate = (id: string) => {
dispatch({ type: 'DUPLICATE_STORY', id });
};
return (
<Sidebar side="left">
<div class={styles.menu}>
@ -129,7 +120,6 @@ export const MenuSidebar = () => {
onSelect={() => handleSelect(story.id)}
onRename={(newTitle) => handleRename(story.id, newTitle)}
onDelete={() => handleDelete(story.id)}
onDuplicate={() => handleDuplicate(story.id)}
/>
))}
</div>

View File

@ -81,7 +81,6 @@ type Action =
| { type: 'SET_CURRENT_TAB'; id: string; tab: Tab }
| { type: 'DELETE_STORY'; id: string }
| { type: 'SELECT_STORY'; id: string }
| { type: 'DUPLICATE_STORY'; id: string }
| { type: 'ADD_CHAT_MESSAGE'; storyId: string; message: ChatMessage }
| { type: 'CLEAR_CHAT'; storyId: string }
| { type: 'SET_CONNECTION'; connection: LLM.Connection | null }
@ -181,26 +180,6 @@ function reducer(state: IState, action: Action): IState {
currentStoryId: deletingCurrent ? null : state.currentStoryId,
};
}
case 'DUPLICATE_STORY': {
const original = state.stories.find(s => s.id === action.id);
if (!original) return state;
const newStory: Story = {
id: crypto.randomUUID(),
title: `${original.title} (Copy)`,
text: '',
lore: original.lore,
characters: original.characters,
locations: original.locations,
currentTab: 'story',
chatMessages: [],
chapters: [],
};
return {
...state,
stories: [...state.stories, newStory],
currentStoryId: newStory.id,
};
}
case 'SELECT_STORY': {
return {
...state,
@ -286,20 +265,11 @@ function reducer(state: IState, action: Action): IState {
case 'DELETE_CHARACTER': {
return {
...state,
stories: state.stories.map(s => {
if (s.id !== action.storyId) return s;
const deletedChar = s.characters.find(c => c.id === action.characterId);
if (!deletedChar) return s;
return {
...s,
characters: s.characters
.filter(c => c.id !== action.characterId)
.map(c => ({
...c,
relations: c.relations.filter(r => r.name !== deletedChar.name),
})),
};
}),
stories: state.stories.map(s =>
s.id === action.storyId
? { ...s, characters: s.characters.filter(c => c.id !== action.characterId) }
: s
),
};
}
case 'ADD_CHARACTER_RELATION': {

View File

@ -1,4 +1,4 @@
import { formatErrorMessage } from "@common/errors";
import { formatError } from "@common/errors";
import { Type, type Static, type TObject } from '@common/typebox';
import { LocationScale, type AppState, type Character, type Location } from "../contexts/state";
import type LLM from "./llm";
@ -10,12 +10,6 @@ const SCALE_DESCRIPTION = Object.entries(LocationScale)
const VALID_SCALES = Object.values(LocationScale).filter(v => typeof v === 'number');
const SCALE_NAMES = Object.fromEntries(
Object.entries(LocationScale)
.filter(([, value]) => typeof value === 'number')
.map(([key, value]) => [value, key])
);
export namespace Tools {
interface Tool<T extends TObject = TObject> {
description: string;
@ -26,7 +20,60 @@ export namespace Tools {
const tool = <T extends TObject = TObject>(t: Tool<T>): Tool<T> => t;
const TOOLS: Record<string, Tool> = {
'get_character': tool({
'add_character': tool({
handler: async (args, appState) => {
if (!appState.currentStory) {
return 'Error: No story selected';
}
// Filter out relations that reference non-existent characters
const existingCharacterNames = appState.currentStory.characters.map(c => c.name);
const invalidRelations: string[] = [];
const validRelations = (args.relations || []).filter(rel => {
if (!existingCharacterNames.includes(rel.name)) {
invalidRelations.push(`${rel.name} (${rel.relation})`);
return false;
}
return true;
});
appState.dispatch({
type: 'ADD_CHARACTER',
storyId: appState.currentStory.id,
character: {
id: crypto.randomUUID(),
name: args.name.trim(),
nicknames: args.nicknames || [],
shortDescription: args.shortDescription.trim(),
description: args.description || '',
relations: validRelations,
},
});
appState.dispatch({
type: 'SET_CURRENT_TAB',
id: appState.currentStory.id,
tab: 'characters'
});
let message = `Character "${args.name.trim()}" added successfully`;
if (invalidRelations.length > 0) {
message += `. Removed invalid relations to non-existent characters: ${invalidRelations.join(', ')}`;
}
return message;
},
description: 'Add a new character to the story',
parameters: Type.Object({
name: Type.String({ description: "The character's full name" }),
shortDescription: Type.String({ description: 'A brief description of the character (one line)' }),
nicknames: Type.Optional(Type.Array(Type.String(), { description: 'Optional list of nicknames' })),
description: Type.Optional(Type.String({ description: 'Optional full character description' })),
relations: Type.Optional(Type.Array(
Type.Object({
name: Type.String({ description: 'Related character name' }),
relation: Type.String({ description: 'Relationship type' }),
}),
{ description: 'Optional list of relationships with other characters' }
)),
}),
}),
'edit_character': tool({
handler: async (args, appState) => {
if (!appState.currentStory) {
return 'Error: No story selected';
@ -35,168 +82,68 @@ export namespace Tools {
if (!character) {
return `Error: Character "${args.name.trim()}" not found`;
}
let result = `# Character: ${character.name}\n\n`;
if (character.nicknames && character.nicknames.length > 0) {
result += `**Nicknames:** ${character.nicknames.join(', ')}\n\n`;
// Only include defined values to avoid setting fields to undefined
const definedUpdates: Partial<Character> = {};
if (args.shortDescription !== undefined) {
definedUpdates.shortDescription = args.shortDescription;
}
result += `**Short Description:** ${character.shortDescription}\n\n`;
if (character.description) {
result += `**Description:** ${character.description}\n\n`;
if (args.description !== undefined) {
definedUpdates.description = args.description;
}
if (character.relations && character.relations.length > 0) {
result += `**Relations:**\n`;
for (const rel of character.relations) {
result += `- ${rel.name}: ${rel.relation}\n`;
}
}
return result.trim();
appState.dispatch({
type: 'EDIT_CHARACTER',
storyId: appState.currentStory.id,
characterId: character.id,
updates: definedUpdates,
});
appState.dispatch({
type: 'SET_CURRENT_TAB',
id: appState.currentStory.id,
tab: 'characters'
});
return `Character "${args.name.trim()}" updated successfully`;
},
description: 'Get full information about a character by name',
description: "Edit an existing character's description",
parameters: Type.Object({
name: Type.String({ description: "The character's full name" }),
name: Type.String({ description: "The character's full name to identify which character to edit" }),
shortDescription: Type.Optional(Type.String({ description: 'Brief description of the character (one line)' })),
description: Type.Optional(Type.String({ description: 'Full character description' })),
}),
}),
'set_character': tool({
'add_location': tool({
handler: async (args, appState) => {
if (!appState.currentStory) {
return 'Error: No story selected';
}
const existingCharacter = appState.currentStory.characters.find(c => c.name === args.name.trim());
if (existingCharacter) {
// Edit existing character
const definedUpdates: Partial<Character> = {};
if (args.shortDescription !== undefined) {
definedUpdates.shortDescription = args.shortDescription;
}
if (args.description !== undefined) {
definedUpdates.description = args.description;
}
if (args.nicknames !== undefined) {
definedUpdates.nicknames = args.nicknames;
}
if (args.relations !== undefined) {
return 'Error: set_character does not support updating relations. Use set_character_relation instead.';
}
appState.dispatch({
type: 'EDIT_CHARACTER',
storyId: appState.currentStory.id,
characterId: existingCharacter.id,
updates: definedUpdates,
});
appState.dispatch({
type: 'SET_CURRENT_TAB',
id: appState.currentStory.id,
tab: 'characters'
});
return `Character "${args.name.trim()}" updated successfully`;
} else {
// Add new character - validate required fields
if (!args.shortDescription) {
return 'Error: shortDescription is required when adding a new character';
}
const existingCharacterNames = new Set(appState.currentStory.characters.map(c => c.name));
const invalidRelations: string[] = [];
for (const rel of args.relations || []) {
if (!existingCharacterNames.has(rel.name)) {
invalidRelations.push(`${rel.name} (${rel.relation})`);
}
}
appState.dispatch({
type: 'ADD_CHARACTER',
storyId: appState.currentStory.id,
character: {
id: crypto.randomUUID(),
name: args.name.trim(),
nicknames: args.nicknames || [],
shortDescription: args.shortDescription.trim(),
description: args.description || '',
relations: args.relations || [],
},
});
appState.dispatch({
type: 'SET_CURRENT_TAB',
id: appState.currentStory.id,
tab: 'characters'
});
let message = `Character "${args.name.trim()}" added successfully`;
if (invalidRelations.length > 0) {
message += `.\nNote: found invalid relations to non-existent characters: ${invalidRelations.join(', ')}`;
}
return message;
}
appState.dispatch({
type: 'ADD_LOCATION',
storyId: appState.currentStory.id,
location: {
id: crypto.randomUUID(),
name: args.name.trim(),
shortDescription: args.shortDescription.trim(),
description: args.description || '',
scale: args.scale,
},
});
appState.dispatch({
type: 'SET_CURRENT_TAB',
id: appState.currentStory.id,
tab: 'locations'
});
return `Location "${args.name.trim()}" added successfully`;
},
description: 'Add or edit a character. If character exists, updates it; otherwise creates new one.',
description: 'Add a new location to the story',
parameters: Type.Object({
name: Type.String({ description: "The character's full name" }),
shortDescription: Type.Optional(Type.String({ description: 'A brief description of the character (one line). Required on a new character.' })),
nicknames: Type.Optional(Type.Array(Type.String(), { description: 'Optional list of nicknames' })),
description: Type.Optional(Type.String({ description: 'Optional full character description' })),
relations: Type.Optional(Type.Array(
Type.Object({
name: Type.String({ description: 'Related character name' }),
relation: Type.String({ description: 'Relationship type' }),
}),
{ description: 'Optional list of relationships with other characters (allowed only when adding a new character)' }
)),
name: Type.String({ description: "The location's full name" }),
shortDescription: Type.String({ description: 'A brief description of the location (one line)' }),
description: Type.Optional(Type.String({ description: 'Optional full location description' })),
scale: Type.Enum(VALID_SCALES, {
description: `Location scale (enum): ${SCALE_DESCRIPTION}`,
}),
}),
}),
'set_character_relation': tool({
handler: async (args, appState) => {
if (!appState.currentStory) {
return 'Error: No story selected';
}
const character = appState.currentStory.characters.find(c => c.name === args.character_name.trim());
if (!character) {
return `Error: Character "${args.character_name.trim()}" not found`;
}
const targetCharacter = appState.currentStory.characters.find(c => c.name === args.target_name.trim());
if (!targetCharacter) {
return `Error: Target character "${args.target_name.trim()}" not found, please add it first.`;
}
const existingRelationIndex = character.relations.findIndex(r => r.name === args.target_name.trim());
if (existingRelationIndex !== -1) {
// Edit existing relation
appState.dispatch({
type: 'EDIT_CHARACTER_RELATION',
storyId: appState.currentStory.id,
characterId: character.id,
targetName: args.target_name.trim(),
updates: { relation: args.relation.trim() },
});
appState.dispatch({
type: 'SET_CURRENT_TAB',
id: appState.currentStory.id,
tab: 'characters'
});
return `Relation updated: "${args.character_name.trim()}" -> "${args.target_name.trim()}" (${args.relation.trim()})`;
} else {
// Add new relation
appState.dispatch({
type: 'ADD_CHARACTER_RELATION',
storyId: appState.currentStory.id,
characterId: character.id,
relation: {
name: args.target_name.trim(),
relation: args.relation.trim(),
},
});
appState.dispatch({
type: 'SET_CURRENT_TAB',
id: appState.currentStory.id,
tab: 'characters'
});
return `Relation added: "${args.character_name.trim()}" -> "${args.target_name.trim()}" (${args.relation.trim()})`;
}
},
description: 'Add or edit a relationship between two characters. If relation exists, updates it; otherwise creates new one.',
parameters: Type.Object({
character_name: Type.String({ description: "The character's full name to add/edit the relation for" }),
target_name: Type.String({ description: "The target character's full name" }),
relation: Type.String({ description: 'The relationship type (e.g., friend, enemy, sibling)' }),
}),
}),
'get_location': tool({
'edit_location': tool({
handler: async (args, appState) => {
if (!appState.currentStory) {
return 'Error: No story selected';
@ -205,81 +152,34 @@ export namespace Tools {
if (!location) {
return `Error: Location "${args.name.trim()}" not found`;
}
let result = `# Location: ${location.name}\n\n`;
result += `**Short Description:** ${location.shortDescription}\n\n`;
if (location.description) {
result += `**Description:** ${location.description}\n\n`;
const definedUpdates: Partial<Location> = {};
if (args.shortDescription !== undefined) {
definedUpdates.shortDescription = args.shortDescription;
}
result += `**Scale:** ${SCALE_NAMES[location.scale]}\n`;
return result.trim();
if (args.description !== undefined) {
definedUpdates.description = args.description;
}
if (args.scale !== undefined) {
definedUpdates.scale = args.scale;
}
appState.dispatch({
type: 'EDIT_LOCATION',
storyId: appState.currentStory.id,
locationId: location.id,
updates: definedUpdates,
});
appState.dispatch({
type: 'SET_CURRENT_TAB',
id: appState.currentStory.id,
tab: 'locations'
});
return `Location "${args.name.trim()}" updated successfully`;
},
description: 'Get full information about a location by name',
description: "Edit an existing location's description",
parameters: Type.Object({
name: Type.String({ description: "The location's full name" }),
}),
}),
'set_location': tool({
handler: async (args, appState) => {
if (!appState.currentStory) {
return 'Error: No story selected';
}
const existingLocation = appState.currentStory.locations.find(l => l.name === args.name.trim());
if (existingLocation) {
// Edit existing location
const definedUpdates: Partial<Location> = {};
if (args.shortDescription) {
definedUpdates.shortDescription = args.shortDescription;
}
if (args.description) {
definedUpdates.description = args.description;
}
if (args.scale != null) {
definedUpdates.scale = args.scale;
}
appState.dispatch({
type: 'EDIT_LOCATION',
storyId: appState.currentStory.id,
locationId: existingLocation.id,
updates: definedUpdates,
});
appState.dispatch({
type: 'SET_CURRENT_TAB',
id: appState.currentStory.id,
tab: 'locations'
});
return `Location "${args.name.trim()}" updated successfully`;
} else {
// Add new location - validate required fields
if (!args.shortDescription) {
return 'Error: shortDescription is required when adding a new location';
}
if (args.scale == null) {
return 'Error: scale is required when adding a new location';
}
appState.dispatch({
type: 'ADD_LOCATION',
storyId: appState.currentStory.id,
location: {
id: crypto.randomUUID(),
name: args.name.trim(),
shortDescription: args.shortDescription.trim(),
description: args.description || '',
scale: args.scale,
},
});
appState.dispatch({
type: 'SET_CURRENT_TAB',
id: appState.currentStory.id,
tab: 'locations'
});
return `Location "${args.name.trim()}" added successfully`;
}
},
description: 'Add or edit a location. If location exists, updates it; otherwise creates new one.',
parameters: Type.Object({
name: Type.String({ description: "The location's full name" }),
shortDescription: Type.Optional(Type.String({ description: 'A brief description of the location (one line). Required when adding a new location.' })),
description: Type.Optional(Type.String({ description: 'Optional full location description' })),
name: Type.String({ description: "The location's full name to identify which location to edit" }),
shortDescription: Type.Optional(Type.String({ description: 'Brief description of the location (one line)' })),
description: Type.Optional(Type.String({ description: 'Full location description' })),
scale: Type.Optional(Type.Enum(VALID_SCALES, {
description: `Location scale (enum): ${SCALE_DESCRIPTION}`,
})),
@ -358,7 +258,7 @@ export namespace Tools {
}
return `${target === 'lore' ? 'Lore' : 'Story'} edited successfully`;
},
description: "Replace text in the story or lore. When old_text is omitted, appends new_text to the target's end. Case-sensitive.",
description: 'Replace text in the story or lore. When old_text is omitted, appends new_text to the target.',
parameters: Type.Object({
new_text: Type.String({ description: 'The new text to replace old_text with, or to append if old_text is omitted' }),
old_text: Type.Optional(Type.String({ description: 'The text to find and replace. If omitted, new_text will be appended' })),
@ -377,16 +277,14 @@ export namespace Tools {
const sources: { name: string; content: string }[] = [
{ name: 'story', content: appState.currentStory.text },
{ name: 'lore', content: appState.currentStory.lore },
...appState.currentStory.characters.flatMap(c => [
{ name: `character:${c.name}`, content: c.name },
{ name: `character:${c.name}`, content: c.shortDescription },
{ name: `character:${c.name}`, content: c.description || '' },
]),
...appState.currentStory.locations.flatMap(l => [
{ name: `location:${l.name}`, content: l.name },
{ name: `location:${l.name}`, content: l.shortDescription },
{ name: `location:${l.name}`, content: l.description || '' },
]),
...appState.currentStory.characters.map(c => ({
name: `character:${c.name}`,
content: `${c.shortDescription}\n${c.description || ''}`.trim(),
})),
...appState.currentStory.locations.map(l => ({
name: `location:${l.name}`,
content: `${l.shortDescription}\n${l.description || ''}`.trim(),
})),
];
const allMatches: { source: string; line: number; content: string }[] = [];
@ -422,7 +320,7 @@ export namespace Tools {
},
description: 'Search for a pattern in the story text, lore, characters, and locations',
parameters: Type.Object({
pattern: Type.String({ description: 'The JS regex pattern to search for' }),
pattern: Type.String({ description: 'The regex pattern to search for' }),
case_sensitive: Type.Optional(Type.Boolean({ description: 'If true, search is case-sensitive (default: false)' })),
limit: Type.Optional(Type.Integer({ description: 'Maximum number of matches to return (default: 20)' })),
}),
@ -480,7 +378,7 @@ export namespace Tools {
}
return JSON.stringify(result);
} catch (err) {
return formatErrorMessage(err);
return formatError(err, 'Error executing tool');
}
}
}