Note editor sidebar, full-doc assist, persistent drafts, version history

NoteEditorView: two-column sidebar layout (project/milestone/tags/assist
always visible), removed assist toggle button, InlineAssistPanel removed.

Writing assist: whole_doc mode rewrites entire document; DiffView.vue
replaces editor during review showing full-document diff. Scope dropdown
in sidebar switches between whole-document and section modes.

Persistent drafts: migration 0022 adds note_drafts (UNIQUE per note+user)
and note_versions (max 20, auto-pruned) tables. Draft saved after generation
completes, restored on editor mount, cleared on accept/reject. Version
snapshot created automatically whenever note body changes on save.

HistoryPanel.vue: version list + DiffView modal, restore button writes
body back to editor.

Config: OLLAMA_NUM_CTX default raised to 65536; assist num_predict now
tracks Config.OLLAMA_NUM_CTX instead of a hardcoded 4096.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-05 17:10:55 -05:00
parent b11a92f32d
commit 9036dfd931
17 changed files with 1275 additions and 278 deletions
@@ -0,0 +1,43 @@
"""Add note_drafts and note_versions tables."""
from alembic import op
revision = "0022"
down_revision = "0021"
def upgrade() -> None:
op.execute("""
CREATE TABLE IF NOT EXISTS note_drafts (
id SERIAL PRIMARY KEY,
note_id INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
proposed_body TEXT NOT NULL,
original_body TEXT NOT NULL,
instruction TEXT NOT NULL DEFAULT '',
scope TEXT NOT NULL DEFAULT 'document',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (note_id, user_id)
)
""")
op.execute("CREATE INDEX IF NOT EXISTS ix_note_drafts_note_id ON note_drafts(note_id)")
op.execute("""
CREATE TABLE IF NOT EXISTS note_versions (
id SERIAL PRIMARY KEY,
note_id INTEGER NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
body TEXT NOT NULL,
title TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
""")
op.execute("CREATE INDEX IF NOT EXISTS ix_note_versions_note_id ON note_versions(note_id)")
def downgrade() -> None:
op.execute("DROP INDEX IF EXISTS ix_note_versions_note_id")
op.execute("DROP TABLE IF EXISTS note_versions")
op.execute("DROP INDEX IF EXISTS ix_note_drafts_note_id")
op.execute("DROP TABLE IF EXISTS note_drafts")
+118
View File
@@ -0,0 +1,118 @@
<script setup lang="ts">
import { computed } from "vue";
import type { DiffLine } from "@/composables/useAssist";
const props = defineProps<{
diff: DiffLine[];
}>();
const insertions = computed(() => props.diff.filter(l => l.type === 'insert').length);
const deletions = computed(() => props.diff.filter(l => l.type === 'delete').length);
function markerFor(type: DiffLine['type']): string {
if (type === 'insert') return '+';
if (type === 'delete') return '';
return ' ';
}
</script>
<template>
<div class="diff-view-full">
<div class="diff-summary-bar">
<span class="diff-summary-ins">+{{ insertions }} insertion{{ insertions !== 1 ? 's' : '' }}</span>
<span class="diff-summary-del">{{ deletions }} deletion{{ deletions !== 1 ? 's' : '' }}</span>
</div>
<div class="diff-scroll">
<div v-if="!diff.length" class="diff-empty">No changes.</div>
<div
v-for="(line, i) in diff"
:key="i"
:class="['diff-line', `diff-${line.type}`]"
>
<span class="diff-marker">{{ markerFor(line.type) }}</span>
<span class="diff-text">{{ line.text }}</span>
</div>
</div>
</div>
</template>
<style scoped>
.diff-view-full {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
border: 1px solid var(--color-input-border);
border-radius: var(--radius-sm);
background: var(--color-bg);
overflow: hidden;
}
.diff-summary-bar {
position: sticky;
top: 0;
flex-shrink: 0;
display: flex;
gap: 1rem;
padding: 0.4rem 0.75rem;
background: var(--color-bg-secondary);
border-bottom: 1px solid var(--color-border);
font-size: 0.78rem;
font-family: monospace;
font-weight: 600;
}
.diff-summary-ins { color: var(--color-success, #2ecc71); }
.diff-summary-del { color: var(--color-danger, #e74c3c); }
.diff-scroll {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 0.3rem 0;
}
.diff-empty {
padding: 0.75rem;
font-size: 0.85rem;
color: var(--color-text-muted);
font-style: italic;
}
.diff-line {
display: flex;
align-items: baseline;
padding: 0.04rem 0.5rem;
line-height: 1.55;
font-family: monospace;
font-size: 0.82rem;
}
.diff-delete {
background: color-mix(in srgb, var(--color-danger, #e74c3c) 12%, transparent);
color: var(--color-danger, #e74c3c);
}
.diff-insert {
background: color-mix(in srgb, var(--color-success, #2ecc71) 12%, transparent);
color: var(--color-success, #2ecc71);
}
.diff-equal {
color: var(--color-text-muted);
}
.diff-marker {
flex-shrink: 0;
width: 1rem;
text-align: center;
user-select: none;
font-weight: 700;
}
.diff-text {
flex: 1;
white-space: pre-wrap;
word-break: break-word;
}
</style>
+271
View File
@@ -0,0 +1,271 @@
<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { apiGet } from "@/api/client";
import DiffView from "@/components/DiffView.vue";
import type { DiffLine } from "@/composables/useAssist";
interface NoteVersion {
id: number;
note_id: number;
title: string;
body?: string;
created_at: string;
}
const props = defineProps<{
noteId: number;
currentBody: string;
}>();
const emit = defineEmits<{
(e: 'restore', body: string): void;
(e: 'close'): void;
}>();
const versions = ref<NoteVersion[]>([]);
const selectedVersion = ref<NoteVersion | null>(null);
const loading = ref(false);
const loadingDetail = ref(false);
const diff = computed<DiffLine[]>(() => {
if (!selectedVersion.value?.body) return [];
const a = props.currentBody;
const b = selectedVersion.value.body;
const aLines = a.split('\n');
const bLines = b.split('\n');
const m = aLines.length, n = bLines.length;
const dp: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = m - 1; i >= 0; i--)
for (let j = n - 1; j >= 0; j--)
dp[i][j] = aLines[i] === bLines[j]
? dp[i+1][j+1] + 1
: Math.max(dp[i+1][j], dp[i][j+1]);
const result: DiffLine[] = [];
let i = 0, j = 0;
while (i < m && j < n) {
if (aLines[i] === bLines[j]) { result.push({ type: 'equal', text: aLines[i++] }); j++; }
else if (dp[i+1][j] >= dp[i][j+1]) result.push({ type: 'delete', text: aLines[i++] });
else result.push({ type: 'insert', text: bLines[j++] });
}
while (i < m) result.push({ type: 'delete', text: aLines[i++] });
while (j < n) result.push({ type: 'insert', text: bLines[j++] });
return result;
});
function formatDate(iso: string): string {
const d = new Date(iso);
return d.toLocaleString(undefined, {
month: 'short', day: 'numeric', year: 'numeric',
hour: '2-digit', minute: '2-digit',
});
}
async function loadVersions() {
loading.value = true;
try {
const data = await apiGet<{ versions: NoteVersion[] }>(
`/api/notes/${props.noteId}/versions`
);
versions.value = data.versions;
if (versions.value.length > 0) {
await selectVersionItem(versions.value[0]);
}
} catch {
// silent
} finally {
loading.value = false;
}
}
async function selectVersionItem(v: NoteVersion) {
if (v.body !== undefined) {
selectedVersion.value = v;
return;
}
loadingDetail.value = true;
try {
const full = await apiGet<NoteVersion>(
`/api/notes/${props.noteId}/versions/${v.id}`
);
// Cache body back onto list item
const listItem = versions.value.find(x => x.id === v.id);
if (listItem) listItem.body = full.body;
selectedVersion.value = full;
} catch {
// silent
} finally {
loadingDetail.value = false;
}
}
function restore() {
if (!selectedVersion.value?.body) return;
emit('restore', selectedVersion.value.body);
}
onMounted(loadVersions);
</script>
<template>
<teleport to="body">
<div class="modal-overlay" @click.self="emit('close')">
<div class="modal-card history-modal">
<div class="history-header">
<h3 class="history-title">Version History</h3>
<button class="history-close" @click="emit('close')">&times;</button>
</div>
<div class="history-body">
<!-- Left: version list -->
<div class="history-list">
<div v-if="loading" class="history-empty">Loading...</div>
<div v-else-if="!versions.length" class="history-empty">No versions yet.</div>
<div
v-for="v in versions"
:key="v.id"
:class="['history-item', { selected: selectedVersion?.id === v.id }]"
@click="selectVersionItem(v)"
>
<div class="history-item-title">{{ v.title || 'Untitled' }}</div>
<div class="history-item-date">{{ formatDate(v.created_at) }}</div>
</div>
</div>
<!-- Right: diff -->
<div class="history-diff">
<div v-if="loadingDetail" class="history-empty">Loading version...</div>
<div v-else-if="!selectedVersion" class="history-empty">Select a version to compare.</div>
<DiffView v-else :diff="diff" />
</div>
</div>
<div class="history-footer">
<button
class="btn-restore"
:disabled="!selectedVersion?.body"
@click="restore"
>Restore this version</button>
<button class="modal-btn" @click="emit('close')">Close</button>
</div>
</div>
</div>
</teleport>
</template>
<style scoped>
.history-modal {
max-width: 900px;
width: 95%;
height: 80vh;
max-height: 700px;
display: flex;
flex-direction: column;
padding: 0;
}
.history-header {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.9rem 1.25rem;
border-bottom: 1px solid var(--color-border);
}
.history-title {
margin: 0;
font-size: 1rem;
}
.history-close {
background: none;
border: none;
font-size: 1.25rem;
cursor: pointer;
color: var(--color-text-muted);
line-height: 1;
padding: 0.1rem 0.3rem;
}
.history-close:hover { color: var(--color-text); }
.history-body {
flex: 1;
min-height: 0;
display: flex;
overflow: hidden;
}
.history-list {
width: 220px;
flex-shrink: 0;
border-right: 1px solid var(--color-border);
overflow-y: auto;
}
.history-item {
padding: 0.6rem 0.9rem;
cursor: pointer;
border-left: 3px solid transparent;
border-bottom: 1px solid var(--color-border);
}
.history-item:hover { background: var(--color-bg-secondary); }
.history-item.selected {
border-left-color: var(--color-primary);
background: var(--color-bg-secondary);
}
.history-item-title {
font-size: 0.85rem;
font-weight: 500;
color: var(--color-text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.history-item-date {
font-size: 0.75rem;
color: var(--color-text-muted);
margin-top: 0.15rem;
}
.history-diff {
flex: 1;
min-width: 0;
overflow: hidden;
display: flex;
flex-direction: column;
padding: 0.5rem;
}
.history-empty {
padding: 1rem;
font-size: 0.85rem;
color: var(--color-text-muted);
font-style: italic;
}
.history-footer {
flex-shrink: 0;
display: flex;
gap: 0.5rem;
justify-content: flex-end;
padding: 0.75rem 1.25rem;
border-top: 1px solid var(--color-border);
}
.btn-restore {
padding: 0.45rem 1rem;
background: var(--color-primary);
color: #fff;
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 0.9rem;
}
.btn-restore:disabled {
opacity: 0.5;
cursor: default;
}
</style>
+119 -49
View File
@@ -1,5 +1,5 @@
import { ref, computed, watch, type Ref } from "vue";
import { apiPost, apiSSEStream, type SSEStreamHandle } from "@/api/client";
import { apiPost, apiPut, apiDelete, apiSSEStream, type SSEStreamHandle } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import {
parseMarkdownSections,
@@ -7,6 +7,7 @@ import {
} from "@/utils/sectionParser";
export type AssistState = "idle" | "streaming" | "review";
export type ScopeMode = "document" | "section";
export interface AssistTarget {
text: string;
@@ -19,6 +20,17 @@ export interface DiffLine {
text: string;
}
export interface NoteDraft {
id: number;
note_id: number;
proposed_body: string;
original_body: string;
instruction: string;
scope: string;
created_at: string;
updated_at: string;
}
function computeDiff(a: string, b: string): DiffLine[] {
const aLines = a.split('\n');
const bLines = b.split('\n');
@@ -41,24 +53,28 @@ function computeDiff(a: string, b: string): DiffLine[] {
return result;
}
export function useAssist(body: Ref<string>) {
export function useAssist(body: Ref<string>, noteId?: Ref<number | null>) {
const toast = useToastStore();
const state = ref<AssistState>("idle");
const scopeMode = ref<ScopeMode>("document");
const sections = ref<MarkdownSection[]>([]);
const selectedSection = ref<MarkdownSection | null>(null);
const customSelection = ref<{ start: number; end: number; text: string } | null>(null);
const instruction = ref("");
const streamingText = ref("");
const proposedText = ref("");
// Full proposed document body (for section mode: body with section replaced)
const proposedFullBody = ref("");
const error = ref("");
const isProofreading = ref(false);
// Snapshot of body at the time a section/selection was chosen
// Snapshot of body at the time generation was started
let bodySnapshot = "";
let streamHandle: SSEStreamHandle | null = null;
const target = computed<AssistTarget | null>(() => {
if (scopeMode.value === 'document') return null;
if (customSelection.value) {
return {
text: customSelection.value.text,
@@ -76,16 +92,16 @@ export function useAssist(body: Ref<string>) {
return null;
});
const canSubmit = computed(
() =>
target.value !== null &&
instruction.value.trim().length > 0 &&
state.value !== "streaming"
const canSubmit = computed(() =>
instruction.value.trim().length > 0 &&
state.value !== "streaming" &&
(scopeMode.value === 'document' || target.value !== null)
);
// Diff always compares full document: original snapshot → proposed
const diff = computed<DiffLine[]>(() => {
if (state.value !== 'review' || !target.value || !proposedText.value) return [];
return computeDiff(target.value.text, proposedText.value);
if (state.value !== 'review' || !proposedFullBody.value) return [];
return computeDiff(bodySnapshot, proposedFullBody.value);
});
function refreshSections() {
@@ -93,21 +109,21 @@ export function useAssist(body: Ref<string>) {
}
function selectSection(section: MarkdownSection) {
scopeMode.value = 'section';
customSelection.value = null;
selectedSection.value = section;
bodySnapshot = body.value;
error.value = "";
}
function selectTextRange(start: number, end: number) {
if (start === end) return;
scopeMode.value = 'section';
selectedSection.value = null;
customSelection.value = {
start,
end,
text: body.value.slice(start, end),
};
bodySnapshot = body.value;
error.value = "";
}
@@ -121,35 +137,84 @@ export function useAssist(body: Ref<string>) {
instruction.value = "";
streamingText.value = "";
proposedText.value = "";
proposedFullBody.value = "";
error.value = "";
state.value = "idle";
isProofreading.value = false;
}
async function _saveDraft() {
if (!noteId?.value) return;
try {
await apiPut(`/api/notes/${noteId.value}/draft`, {
proposed_body: proposedFullBody.value,
original_body: bodySnapshot,
instruction: instruction.value,
scope: scopeMode.value,
});
} catch {
// Non-critical — ignore draft save errors
}
}
async function _deleteDraft() {
if (!noteId?.value) return;
try {
await apiDelete(`/api/notes/${noteId.value}/draft`);
} catch {
// Ignore — draft may not exist
}
}
async function submit() {
if (!canSubmit.value || !target.value) return;
if (!canSubmit.value) return;
bodySnapshot = body.value;
state.value = "streaming";
streamingText.value = "";
proposedText.value = "";
proposedFullBody.value = "";
error.value = "";
const wholeDoc = scopeMode.value === 'document';
const targetSection = wholeDoc ? body.value : (target.value?.text ?? "");
try {
// Step 1: Launch background generation
await apiPost("/api/notes/assist", {
body: body.value,
target_section: target.value.text,
target_section: targetSection,
instruction: instruction.value,
whole_doc: wholeDoc,
});
// Step 2: Tail the SSE buffer
streamHandle = apiSSEStream("/api/notes/assist/stream", (evt) => {
streamHandle = apiSSEStream("/api/notes/assist/stream", async (evt) => {
if (evt.event === "chunk") {
streamingText.value += evt.data.chunk as string;
}
if (evt.event === "done") {
proposedText.value = (evt.data.full_text as string) || streamingText.value;
const fullText = (evt.data.full_text as string) || streamingText.value;
proposedText.value = fullText;
if (wholeDoc) {
proposedFullBody.value = fullText;
} else {
// Reconstruct full body with section replaced
const t = target.value;
if (t) {
let text = fullText;
if (!text.endsWith("\n")) text += "\n";
proposedFullBody.value =
bodySnapshot.slice(0, t.startOffset) +
text +
bodySnapshot.slice(t.endOffset);
} else {
proposedFullBody.value = fullText;
}
}
state.value = "review";
streamHandle = null;
await _saveDraft();
}
if (evt.event === "error") {
error.value = evt.data.error as string;
@@ -161,11 +226,26 @@ export function useAssist(body: Ref<string>) {
await streamHandle.done;
// Fallback: if stream ended without done/error, use accumulated text
if (state.value === "streaming") {
if (streamingText.value) {
proposedText.value = streamingText.value;
if (wholeDoc) {
proposedFullBody.value = streamingText.value;
} else {
const t = target.value;
if (t) {
let text = streamingText.value;
if (!text.endsWith("\n")) text += "\n";
proposedFullBody.value =
bodySnapshot.slice(0, t.startOffset) +
text +
bodySnapshot.slice(t.endOffset);
} else {
proposedFullBody.value = streamingText.value;
}
}
state.value = "review";
await _saveDraft();
} else {
state.value = "idle";
}
@@ -182,9 +262,9 @@ export function useAssist(body: Ref<string>) {
async function proofread() {
if (state.value === 'streaming') return;
isProofreading.value = true;
scopeMode.value = 'document';
selectedSection.value = null;
customSelection.value = { start: 0, end: body.value.length, text: body.value };
bodySnapshot = body.value;
customSelection.value = null;
error.value = '';
instruction.value =
"Proofread for clarity, grammar, spelling, and flow. " +
@@ -194,60 +274,48 @@ export function useAssist(body: Ref<string>) {
}
function accept(): string {
if (!target.value || !proposedText.value) return body.value;
const result = proposedFullBody.value || body.value;
const t = target.value;
// Validate that the body hasn't changed at the target offsets
if (body.value !== bodySnapshot) {
const currentSlice = body.value.slice(t.startOffset, t.endOffset);
if (currentSlice !== t.text) {
error.value = "The document changed since this suggestion was made. Please clear and try again.";
toast.show(error.value, "error");
state.value = "idle";
return body.value;
}
}
// Ensure proposed text ends with a newline for clean separation
let text = proposedText.value;
if (!text.endsWith("\n")) {
text += "\n";
}
const newBody =
body.value.slice(0, t.startOffset) +
text +
body.value.slice(t.endOffset);
// Reset state
selectedSection.value = null;
customSelection.value = null;
streamingText.value = "";
proposedText.value = "";
proposedFullBody.value = "";
error.value = "";
state.value = "idle";
isProofreading.value = false;
return newBody;
_deleteDraft();
return result;
}
function reject() {
proposedText.value = "";
proposedFullBody.value = "";
streamingText.value = "";
error.value = "";
state.value = "idle";
isProofreading.value = false;
_deleteDraft();
// Keep selection + instruction for retry
}
// Keep sections in sync with body automatically
function loadDraft(draft: NoteDraft) {
bodySnapshot = draft.original_body;
proposedText.value = draft.proposed_body;
proposedFullBody.value = draft.proposed_body;
instruction.value = draft.instruction;
scopeMode.value = draft.scope as ScopeMode;
state.value = "review";
}
watch(body, () => {
refreshSections();
}, { immediate: true });
return {
state,
scopeMode,
sections,
selectedSection,
customSelection,
@@ -255,6 +323,7 @@ export function useAssist(body: Ref<string>) {
instruction,
streamingText,
proposedText,
proposedFullBody,
error,
canSubmit,
diff,
@@ -267,5 +336,6 @@ export function useAssist(body: Ref<string>) {
proofread,
accept,
reject,
loadDraft,
};
}
+19
View File
@@ -13,3 +13,22 @@ export interface TaskLog {
created_at: string;
updated_at: string;
}
export interface NoteDraft {
id: number;
note_id: number;
proposed_body: string;
original_body: string;
instruction: string;
scope: string;
created_at: string;
updated_at: string;
}
export interface NoteVersion {
id: number;
note_id: number;
title: string;
body?: string;
created_at: string;
}
+376 -196
View File
@@ -4,15 +4,16 @@ import { useRoute, useRouter, onBeforeRouteLeave } from "vue-router";
import { useNotesStore } from "@/stores/notes";
import { useToastStore } from "@/stores/toast";
import { renderMarkdown } from "@/utils/markdown";
import { useAssist } from "@/composables/useAssist";
import { apiPost } from "@/api/client";
import { useAssist, type NoteDraft } from "@/composables/useAssist";
import { apiPost, apiGet } from "@/api/client";
import type { Editor } from "@tiptap/vue-3";
import MarkdownToolbar from "@/components/MarkdownToolbar.vue";
import TiptapEditor from "@/components/TiptapEditor.vue";
import TagInput from "@/components/TagInput.vue";
import ProjectSelector from "@/components/ProjectSelector.vue";
import MilestoneSelector from "@/components/MilestoneSelector.vue";
import InlineAssistPanel from "@/components/InlineAssistPanel.vue";
import DiffView from "@/components/DiffView.vue";
import HistoryPanel from "@/components/HistoryPanel.vue";
const route = useRoute();
const router = useRouter();
@@ -27,6 +28,8 @@ const milestoneId = ref<number | null>(null);
const dirty = ref(false);
const saving = ref(false);
const showPreview = ref(false);
const sidebarOpen = ref(true);
const showHistory = ref(false);
const editorRef = ref<InstanceType<typeof TiptapEditor> | null>(null);
const tiptapEditor = computed<Editor | null>(() => {
return (editorRef.value?.editor as Editor | undefined) ?? null;
@@ -39,24 +42,46 @@ const isEditing = computed(() => noteId.value !== null);
const renderedPreview = computed(() => renderMarkdown(body.value));
// AI Assist
const assist = useAssist(body);
// AI Assist — pass noteId for draft persistence
const assist = useAssist(body, noteId);
const assistLabel = computed(() => {
if (assist.isProofreading.value) return "Proofreading document...";
const t = assist.target.value;
if (!t) return "Generating...";
const heading = t.text.split("\n")[0];
return `Revising: "${heading.length > 50 ? heading.slice(0, 50) + "..." : heading}"`;
// Scope selector options: "Whole document" + one per section
const scopeOptions = computed(() => {
const opts: Array<{ value: string; label: string }> = [
{ value: '__document__', label: 'Whole document' },
];
for (const section of assist.sections.value) {
opts.push({
value: String(assist.sections.value.indexOf(section)),
label: section.heading || '(preamble)',
});
}
return opts;
});
// Assist panel toggle (persisted)
const ASSIST_KEY = 'fa-assist-open';
const assistOpen = ref(localStorage.getItem(ASSIST_KEY) !== 'false');
function toggleAssist() {
assistOpen.value = !assistOpen.value;
localStorage.setItem(ASSIST_KEY, String(assistOpen.value));
}
const scopeSelectValue = computed({
get() {
if (assist.scopeMode.value === 'document') return '__document__';
if (assist.selectedSection.value) {
const idx = assist.sections.value.indexOf(assist.selectedSection.value);
return idx >= 0 ? String(idx) : '__document__';
}
return '__document__';
},
set(val: string) {
if (val === '__document__') {
assist.scopeMode.value = 'document';
assist.selectedSection.value = null;
} else {
const idx = Number(val);
const section = assist.sections.value[idx];
if (section) {
assist.scopeMode.value = 'section';
assist.selectSection(section);
}
}
},
});
// Floating inline assist button
const floatingAssist = ref({ show: false, top: 0, left: 0 });
@@ -79,25 +104,17 @@ function onSelectionChange(payload: { text: string; start: number; end: number }
function handleInlineAssist() {
if (!pendingSelection.value) return;
assist.scopeMode.value = 'section';
assist.selectTextRange(pendingSelection.value.start, pendingSelection.value.end);
assistOpen.value = true;
localStorage.setItem(ASSIST_KEY, 'true');
floatingAssist.value.show = false;
nextTick(() => instructionRef.value?.focus());
}
function handleAssistAccept() {
const newBody = assist.accept();
if (newBody !== body.value) {
body.value = newBody;
markDirty();
toast.show("Section updated");
}
}
function truncateTarget(text: string, max = 60): string {
const first = text.split("\n")[0];
return first.length > max ? first.slice(0, max) + "..." : first;
body.value = newBody;
markDirty();
toast.show("Document updated");
}
// Tag suggestions
@@ -174,6 +191,14 @@ onMounted(async () => {
savedProjectId = projectId.value;
savedMilestoneId = milestoneId.value;
}
// Restore pending draft if any
try {
const draft = await apiGet<NoteDraft>(`/api/notes/${noteId.value}/draft`);
if (draft) assist.loadDraft(draft);
} catch {
// No draft — normal
}
}
});
@@ -218,9 +243,7 @@ async function save() {
const showDeleteConfirm = ref(false);
function remove() {
if (noteId.value) {
showDeleteConfirm.value = true;
}
if (noteId.value) showDeleteConfirm.value = true;
}
async function confirmDelete() {
@@ -236,14 +259,17 @@ async function confirmDelete() {
}
}
// Auto-save every 5 minutes when editing an existing note
// Auto-save every 5 minutes
let autoSaveTimer: ReturnType<typeof setInterval> | null = null;
async function autoSave() {
if (!isEditing.value || !dirty.value || saving.value) return;
saving.value = true;
try {
await store.updateNote(noteId.value!, { title: title.value, body: body.value, tags: tags.value, project_id: projectId.value, milestone_id: milestoneId.value } as Record<string, unknown>);
await store.updateNote(noteId.value!, {
title: title.value, body: body.value, tags: tags.value,
project_id: projectId.value, milestone_id: milestoneId.value,
} as Record<string, unknown>);
savedTitle = title.value;
savedBody = body.value;
savedTags = [...tags.value];
@@ -252,7 +278,7 @@ async function autoSave() {
dirty.value = false;
toast.show("Auto-saved");
} catch {
// Silent — user can still save manually
// Silent
} finally {
saving.value = false;
}
@@ -261,7 +287,6 @@ async function autoSave() {
onMounted(() => { autoSaveTimer = setInterval(autoSave, 5 * 60 * 1000); });
onUnmounted(() => { if (autoSaveTimer !== null) clearInterval(autoSaveTimer); });
// Ctrl+S handler
function onKeydown(e: KeyboardEvent) {
if ((e.ctrlKey || e.metaKey) && e.key === "s") {
e.preventDefault();
@@ -272,37 +297,27 @@ function onKeydown(e: KeyboardEvent) {
onMounted(() => document.addEventListener("keydown", onKeydown));
onUnmounted(() => document.removeEventListener("keydown", onKeydown));
// Unsaved changes guard — in-app navigation
onBeforeRouteLeave(() => {
if (dirty.value) {
return confirm("You have unsaved changes. Leave anyway?");
}
if (dirty.value) return confirm("You have unsaved changes. Leave anyway?");
});
// Unsaved changes guard — browser close/reload
function onBeforeUnload(e: BeforeUnloadEvent) {
if (dirty.value) {
e.preventDefault();
}
if (dirty.value) e.preventDefault();
}
onMounted(() => window.addEventListener("beforeunload", onBeforeUnload));
onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
</script>
<template>
<main class="editor-page">
<main class="editor-page note-editor-page">
<div class="editor-header">
<div class="toolbar">
<router-link to="/notes" class="btn-back">Back</router-link>
<button class="btn-save" @click="save" :disabled="saving">
{{ saving ? "Saving..." : "Save" }}
</button>
<button v-if="isEditing" class="btn-delete" @click="remove">
Delete
</button>
<button class="btn-assist-toggle" :class="{ active: assistOpen }" @click="toggleAssist">
Assist
</button>
<button v-if="isEditing" class="btn-delete" @click="remove">Delete</button>
<button v-if="isEditing" class="btn-history" @click="showHistory = true">History</button>
</div>
<input
v-model="title"
@@ -311,133 +326,129 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
class="title-input"
@input="markDirty"
/>
<div class="field-row-meta">
<div class="meta-field">
<label class="meta-label">Project</label>
<ProjectSelector v-model="projectId" @update:modelValue="milestoneId = null; markDirty()" />
</div>
<div class="meta-field">
<label class="meta-label">Milestone</label>
<MilestoneSelector :projectId="projectId" v-model="milestoneId" @update:modelValue="markDirty" />
</div>
</div>
<TagInput
v-model="tags"
:fetchTags="(q: string) => store.fetchAllTags(q)"
@update:modelValue="markDirty"
/>
<div class="tag-suggest-row">
<button class="btn-suggest-tags" @click="fetchTagSuggestions" :disabled="suggestingTags">
{{ suggestingTags ? "Suggesting..." : "Suggest tags" }}
</button>
<template v-if="suggestedTags.length > 0">
<button
v-for="tag in suggestedTags"
:key="tag"
:class="['tag-pill', { applied: appliedTags.has(tag) }]"
:disabled="appliedTags.has(tag)"
@click="applyTagSuggestion(tag)"
>
#{{ tag }}
<span v-if="appliedTags.has(tag)" class="tag-check">&#10003;</span>
</button>
<button class="btn-dismiss-tags" @click="dismissTagSuggestions">&times;</button>
</template>
</div>
<div class="editor-tabs">
<button
:class="['tab', { active: !showPreview }]"
@click="showPreview = false"
>
Write
</button>
<button
:class="['tab', { active: showPreview }]"
@click="showPreview = true"
>
Preview
</button>
</div>
<MarkdownToolbar v-show="!showPreview" :editor="tiptapEditor" />
</div>
<div class="editor-body">
<div class="editor-main">
<!-- Inline assist output: streaming preview + review diff -->
<InlineAssistPanel
v-if="assist.state.value !== 'idle'"
:phase="assist.state.value as 'streaming' | 'review'"
:label="assistLabel"
:streaming-text="assist.streamingText.value"
:diff="assist.diff.value"
:proposed-text="assist.proposedText.value"
@accept="handleAssistAccept"
@reject="assist.reject()"
@cancel="assist.clearSelection()"
/>
<!-- Two-column body: main | sidebar -->
<div class="note-body">
<!-- Editor hidden during review so diff takes full column -->
<div v-show="!showPreview && assist.state.value !== 'review'">
<TiptapEditor
ref="editorRef"
:modelValue="body"
placeholder="Write your note in Markdown..."
@update:modelValue="onBodyUpdate"
@selectionChange="onSelectionChange"
/>
<!-- Main column -->
<div class="note-main">
<div class="body-tabs-row">
<div class="editor-tabs">
<button :class="['tab', { active: !showPreview }]" @click="showPreview = false">Write</button>
<button :class="['tab', { active: showPreview }]" @click="showPreview = true">Preview</button>
</div>
<MarkdownToolbar v-show="!showPreview && assist.state.value === 'idle'" :editor="tiptapEditor" />
</div>
<div
v-show="showPreview && assist.state.value !== 'review'"
class="preview-pane prose"
v-html="renderedPreview"
></div>
<!-- Streaming preview -->
<template v-if="assist.state.value === 'streaming'">
<div class="stream-label">Generating...</div>
<div class="stream-preview prose" v-html="renderMarkdown(assist.streamingText.value)" />
</template>
<!-- Review: full-document diff -->
<template v-else-if="assist.state.value === 'review'">
<DiffView :diff="assist.diff.value" class="main-diff" />
</template>
<!-- Normal editor -->
<template v-else>
<div v-show="!showPreview" class="body-editor-wrap">
<TiptapEditor
ref="editorRef"
:modelValue="body"
placeholder="Write your note in Markdown..."
@update:modelValue="onBodyUpdate"
@selectionChange="onSelectionChange"
/>
</div>
<div
v-show="showPreview"
class="preview-pane prose"
v-html="renderedPreview"
/>
</template>
<!-- Error from assist -->
<div v-if="assist.error.value" class="assist-error">{{ assist.error.value }}</div>
</div>
<aside v-if="assistOpen" class="assist-panel">
<!-- Panel header -->
<div class="assist-panel-header">
<span class="assist-panel-title"> AI Assist</span>
<button
class="btn-proofread"
@click="assist.proofread()"
:disabled="assist.state.value === 'streaming'"
>Proofread</button>
<button class="btn-close-assist" @click="toggleAssist">×</button>
</div>
<!-- Sidebar -->
<aside class="note-sidebar">
<button class="sidebar-toggle" @click="sidebarOpen = !sidebarOpen">
Details {{ sidebarOpen ? '' : '' }}
</button>
<!-- Panel body -->
<div class="assist-panel-body">
<div :class="['sidebar-content', { 'sidebar-open': sidebarOpen }]">
<!-- IDLE -->
<div v-if="assist.state.value === 'idle'" class="assist-idle">
<div class="assist-sections-label">Sections</div>
<div class="assist-sections">
<div
v-for="(section, i) in assist.sections.value"
:key="i"
:class="['assist-section-item', { selected: assist.selectedSection.value === section }]"
@click="assist.selectSection(section)"
<!-- Project / Milestone / Tags -->
<div class="sb-field">
<label class="sb-label">Project</label>
<ProjectSelector
v-model="projectId"
@update:modelValue="milestoneId = null; markDirty()"
/>
</div>
<div v-if="projectId" class="sb-field">
<label class="sb-label">Milestone</label>
<MilestoneSelector
:projectId="projectId"
v-model="milestoneId"
@update:modelValue="markDirty"
/>
</div>
<div class="sb-field">
<label class="sb-label">Tags</label>
<TagInput
v-model="tags"
:fetchTags="(q: string) => store.fetchAllTags(q)"
@update:modelValue="markDirty"
/>
</div>
<div class="tag-suggest-row">
<button class="btn-suggest-tags" @click="fetchTagSuggestions" :disabled="suggestingTags">
{{ suggestingTags ? "Suggesting..." : "Suggest tags" }}
</button>
<template v-if="suggestedTags.length > 0">
<button
v-for="tag in suggestedTags"
:key="tag"
:class="['tag-pill', { applied: appliedTags.has(tag) }]"
:disabled="appliedTags.has(tag)"
@click="applyTagSuggestion(tag)"
>
{{ section.heading || '(preamble)' }}
</div>
<div v-if="!assist.sections.value.length" class="assist-empty">
Write some content to get started.
</div>
#{{ tag }}
<span v-if="appliedTags.has(tag)" class="tag-check">&#10003;</span>
</button>
<button class="btn-dismiss-tags" @click="dismissTagSuggestions">&times;</button>
</template>
</div>
<div class="sb-divider"></div>
<!-- Writing Assistant (always visible) -->
<div class="assist-section">
<div class="assist-section-title"> Writing Assistant</div>
<!-- Scope selector -->
<div class="sb-field">
<label class="sb-label">Scope</label>
<select v-model="scopeSelectValue" class="sb-select" :disabled="assist.state.value === 'streaming'">
<option
v-for="opt in scopeOptions"
:key="opt.value"
:value="opt.value"
>{{ opt.label }}</option>
</select>
</div>
<template v-if="assist.target.value">
<div class="assist-target-preview">
Editing: <em>{{ truncateTarget(assist.target.value.text) }}</em>
</div>
<!-- Idle: instruction + buttons -->
<template v-if="assist.state.value === 'idle'">
<textarea
ref="instructionRef"
v-model="assist.instruction.value"
placeholder="What should I do with this section?"
placeholder="What should I do?"
class="assist-instruction"
rows="3"
></textarea>
@@ -447,38 +458,52 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
@click="assist.submit()"
:disabled="!assist.canSubmit.value"
>Generate</button>
<button class="btn-clear" @click="assist.clearSelection()">Clear</button>
<button
class="btn-proofread"
@click="assist.proofread()"
>Proofread</button>
</div>
</template>
<!-- Streaming: cancel -->
<template v-else-if="assist.state.value === 'streaming'">
<div class="assist-active-hint">Generating see main area</div>
<button class="btn-clear" @click="assist.clearSelection()">Cancel</button>
</template>
<!-- Review: accept / reject -->
<template v-else-if="assist.state.value === 'review'">
<div class="assist-active-hint">Review the diff in the main area</div>
<div class="assist-actions">
<button class="btn-accept" @click="handleAssistAccept">Accept</button>
<button class="btn-reject" @click="assist.reject()">Reject</button>
</div>
</template>
<div v-else class="assist-hint">
Select a section above or highlight text in the editor.
</div>
</div>
<!-- ERROR -->
<div v-if="assist.error.value" class="assist-error">{{ assist.error.value }}</div>
<!-- Hint when active (output shown inline in editor area) -->
<div v-if="assist.state.value !== 'idle'" class="assist-active-hint">
{{ assist.state.value === 'streaming' ? 'Generating in editor' : 'Review diff in editor ' }}
</div>
</div>
</div><!-- /sidebar-content -->
</aside>
</div>
</div><!-- /note-body -->
<!-- Floating inline assist button (teleported to body) -->
<!-- Floating inline assist button -->
<teleport to="body">
<button
v-if="floatingAssist.show"
class="inline-assist-btn"
:style="{ top: floatingAssist.top + 'px', left: floatingAssist.left + 'px' }"
@mousedown.prevent="handleInlineAssist"
>
Assist
</button>
> Assist</button>
</teleport>
<!-- History panel -->
<HistoryPanel
v-if="showHistory && noteId"
:note-id="noteId"
:current-body="body"
@restore="body = $event; markDirty()"
@close="showHistory = false"
/>
<!-- Delete confirmation -->
<teleport to="body">
<div v-if="showDeleteConfirm" class="modal-overlay" @click="showDeleteConfirm = false">
@@ -497,23 +522,178 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
<style src="@/assets/editor-shared.css" />
<style scoped>
.field-row-meta {
display: flex;
gap: 1rem;
flex-wrap: wrap;
margin-bottom: 0.25rem;
/* ── Two-column note layout ──────────────────────────────────── */
.note-editor-page {
max-width: 1600px;
}
.meta-field {
.note-body {
flex: 1;
min-height: 0;
display: flex;
overflow: hidden;
position: relative;
}
/* Main column */
.note-main {
flex: 1;
min-width: 0;
overflow-y: auto;
padding: 0.75rem 1.25rem 2rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.body-tabs-row {
display: flex;
flex-direction: column;
gap: 0.25rem;
min-width: 180px;
flex: 1;
max-width: 300px;
}
.meta-label {
.body-editor-wrap {
min-height: 200px;
}
.stream-label {
font-size: 0.8rem;
color: var(--color-text-secondary);
font-weight: 500;
color: var(--color-text-muted);
font-style: italic;
}
</style>
.stream-preview {
border: 1px solid var(--color-input-border);
border-radius: var(--radius-sm);
padding: 0.75rem;
background: var(--color-bg-card);
min-height: 200px;
}
.main-diff {
flex: 1;
min-height: 0;
}
/* Right sidebar */
.note-sidebar {
width: 280px;
flex-shrink: 0;
border-left: 1px solid var(--color-border);
overflow-y: auto;
display: flex;
flex-direction: column;
}
/* Mobile accordion toggle (hidden on desktop) */
.sidebar-toggle {
display: none;
width: 100%;
padding: 0.6rem 1rem;
background: var(--color-bg-secondary);
border: none;
border-bottom: 1px solid var(--color-border);
font-size: 0.85rem;
font-weight: 600;
color: var(--color-text-secondary);
cursor: pointer;
text-align: left;
font-family: inherit;
}
.sidebar-content {
padding: 0.75rem;
display: flex;
flex-direction: column;
gap: 0.65rem;
}
/* Sidebar field layout */
.sb-field {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.sb-label {
font-size: 0.78rem;
font-weight: 600;
color: var(--color-text-secondary);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.sb-select {
width: 100%;
padding: 0.35rem 0.5rem;
border: 1px solid var(--color-input-border);
border-radius: var(--radius-sm);
background: var(--color-bg-card);
color: var(--color-text);
font-size: 0.875rem;
font-family: inherit;
box-sizing: border-box;
}
.sb-select:focus { outline: none; border-color: var(--color-primary); }
.sb-divider {
height: 1px;
background: var(--color-border);
margin: 0.15rem 0;
}
/* Tag suggest row inside sidebar */
.tag-suggest-row {
display: flex;
flex-wrap: wrap;
gap: 0.3rem;
align-items: center;
}
/* Writing Assistant section */
.assist-section {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.assist-section-title {
font-size: 0.78rem;
font-weight: 700;
color: var(--color-text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
}
/* History button */
.btn-history {
padding: 0.45rem 1rem;
background: none;
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 0.875rem;
color: var(--color-text-secondary);
font-family: inherit;
}
.btn-history:hover {
border-color: var(--color-primary);
color: var(--color-primary);
}
/* Narrow screen: sidebar collapses */
@media (max-width: 720px) {
.note-body { flex-direction: column; overflow-y: auto; overflow-x: hidden; }
.note-main { padding: 0.75rem 1rem 1rem; overflow-y: visible; }
.note-sidebar {
width: 100%;
border-left: none;
border-top: 1px solid var(--color-border);
overflow-y: visible;
}
.sidebar-toggle { display: block; }
.sidebar-content {
display: none;
padding: 0.75rem 1rem;
}
.sidebar-content.sidebar-open { display: flex; }
}
</style>
+3 -2
View File
@@ -24,8 +24,9 @@ class Config:
)
OLLAMA_URL: str = os.environ.get("OLLAMA_URL", "http://localhost:11434")
OLLAMA_MODEL: str = os.environ.get("OLLAMA_MODEL", "qwen3:latest")
# KV cache context window for generation. Lower = less VRAM, less throughput impact.
OLLAMA_NUM_CTX: int = int(os.environ.get("OLLAMA_NUM_CTX", "16384"))
# KV cache context window for generation. Higher = more RAM usage but longer inputs/outputs.
# 131072 is the practical maximum for most models. Lower this on RAM-constrained hosts.
OLLAMA_NUM_CTX: int = int(os.environ.get("OLLAMA_NUM_CTX", "65536"))
SECRET_KEY: str = _read_secret("SECRET_KEY", "SECRET_KEY_FILE", "dev-secret-change-me")
SECURE_COOKIES: bool = os.environ.get("SECURE_COOKIES", "").lower() in ("1", "true", "yes")
LOG_LEVEL: str = os.environ.get("LOG_LEVEL", "INFO")
+2
View File
@@ -30,3 +30,5 @@ from fabledassistant.models.push_subscription import PushSubscription # noqa: E
from fabledassistant.models.event import Event # noqa: E402, F401
from fabledassistant.models.milestone import Milestone # noqa: E402, F401
from fabledassistant.models.task_log import TaskLog # noqa: E402, F401
from fabledassistant.models.note_draft import NoteDraft # noqa: E402, F401
from fabledassistant.models.note_version import NoteVersion # noqa: E402, F401
+39
View File
@@ -0,0 +1,39 @@
from datetime import datetime, timezone
from sqlalchemy import DateTime, ForeignKey, Integer, Text
from sqlalchemy.orm import Mapped, mapped_column
from fabledassistant.models import Base
class NoteDraft(Base):
__tablename__ = "note_drafts"
id: Mapped[int] = mapped_column(primary_key=True)
note_id: Mapped[int] = mapped_column(Integer, ForeignKey("notes.id", ondelete="CASCADE"))
user_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id", ondelete="CASCADE"))
proposed_body: Mapped[str] = mapped_column(Text)
original_body: Mapped[str] = mapped_column(Text)
instruction: Mapped[str] = mapped_column(Text, default="")
scope: Mapped[str] = mapped_column(Text, default="document")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
onupdate=lambda: datetime.now(timezone.utc),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"note_id": self.note_id,
"user_id": self.user_id,
"proposed_body": self.proposed_body,
"original_body": self.original_body,
"instruction": self.instruction,
"scope": self.scope,
"created_at": self.created_at.isoformat(),
"updated_at": self.updated_at.isoformat(),
}
@@ -0,0 +1,31 @@
from datetime import datetime, timezone
from sqlalchemy import DateTime, ForeignKey, Integer, Text
from sqlalchemy.orm import Mapped, mapped_column
from fabledassistant.models import Base
class NoteVersion(Base):
__tablename__ = "note_versions"
id: Mapped[int] = mapped_column(primary_key=True)
note_id: Mapped[int] = mapped_column(Integer, ForeignKey("notes.id", ondelete="CASCADE"))
user_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id", ondelete="CASCADE"))
body: Mapped[str] = mapped_column(Text)
title: Mapped[str] = mapped_column(Text, default="")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
def to_dict(self, include_body: bool = True) -> dict:
d: dict = {
"id": self.id,
"note_id": self.note_id,
"user_id": self.user_id,
"title": self.title,
"created_at": self.created_at.isoformat(),
}
if include_body:
d["body"] = self.body
return d
+69 -3
View File
@@ -30,6 +30,8 @@ from fabledassistant.services.notes import (
)
from fabledassistant.services.settings import get_setting
from fabledassistant.services.tag_suggestions import suggest_tags
from fabledassistant.services.note_drafts import upsert_draft, get_draft, delete_draft
from fabledassistant.services.note_versions import list_versions, get_version
logger = logging.getLogger(__name__)
@@ -285,11 +287,15 @@ async def assist_route():
target_section = data.get("target_section", "")
instruction = data.get("instruction", "")
if not target_section or not instruction:
return jsonify({"error": "target_section and instruction are required"}), 400
whole_doc = bool(data.get("whole_doc", False))
if not whole_doc and not target_section:
return jsonify({"error": "target_section is required for section mode"}), 400
if not instruction:
return jsonify({"error": "instruction is required"}), 400
model = await get_setting(uid, "default_model", Config.OLLAMA_MODEL) or Config.OLLAMA_MODEL
messages = build_assist_messages(body, target_section, instruction)
messages = build_assist_messages(body, target_section, instruction, whole_doc=whole_doc)
buf = create_assist_buffer(uid)
asyncio.create_task(run_assist_generation(buf, messages, model))
@@ -336,3 +342,63 @@ async def assist_stream_route():
"X-Accel-Buffering": "no",
},
)
# ── Draft routes ─────────────────────────────────────────────────────────────
@notes_bp.route("/<int:note_id>/draft", methods=["GET"])
@login_required
async def get_draft_route(note_id: int):
uid = get_current_user_id()
draft = await get_draft(uid, note_id)
if draft is None:
return jsonify({"error": "No draft found"}), 404
return jsonify(draft.to_dict())
@notes_bp.route("/<int:note_id>/draft", methods=["PUT"])
@login_required
async def upsert_draft_route(note_id: int):
uid = get_current_user_id()
# Verify note ownership
note = await get_note(uid, note_id)
if note is None:
return jsonify({"error": "Note not found"}), 404
data = await request.get_json()
draft = await upsert_draft(
user_id=uid,
note_id=note_id,
proposed_body=data.get("proposed_body", ""),
original_body=data.get("original_body", ""),
instruction=data.get("instruction", ""),
scope=data.get("scope", "document"),
)
return jsonify(draft.to_dict()), 200
@notes_bp.route("/<int:note_id>/draft", methods=["DELETE"])
@login_required
async def delete_draft_route(note_id: int):
uid = get_current_user_id()
await delete_draft(uid, note_id)
return "", 204
# ── Version routes ────────────────────────────────────────────────────────────
@notes_bp.route("/<int:note_id>/versions", methods=["GET"])
@login_required
async def list_versions_route(note_id: int):
uid = get_current_user_id()
versions = await list_versions(uid, note_id)
return jsonify({"versions": [v.to_dict(include_body=False) for v in versions]})
@notes_bp.route("/<int:note_id>/versions/<int:version_id>", methods=["GET"])
@login_required
async def get_version_route(note_id: int, version_id: int):
uid = get_current_user_id()
version = await get_version(uid, note_id, version_id)
if version is None:
return jsonify({"error": "Version not found"}), 404
return jsonify(version.to_dict(include_body=True))
+38 -25
View File
@@ -2,38 +2,51 @@ MAX_BODY_CHARS = 8000
def build_assist_messages(
body: str, target_section: str, instruction: str
body: str, target_section: str, instruction: str, whole_doc: bool = False
) -> list[dict]:
"""Build Ollama messages for section-level assist.
"""Build Ollama messages for writing assist.
The full note body (truncated) is provided as read-only context in the
system prompt. The target section + user instruction go in the user
message. The model outputs only the replacement for the target section.
When whole_doc=True, the model revises the entire document.
When whole_doc=False (section mode), the full body is provided as read-only
context and the model outputs only the replacement for the target section.
"""
truncated_body = body[:MAX_BODY_CHARS]
if len(body) > MAX_BODY_CHARS:
truncated_body += "\n... (truncated)"
system_content = (
"You are an AI writing assistant integrated into a note-taking app. "
"The user is editing a document. The full document is shown below for context.\n\n"
f"--- Full Document ---\n{truncated_body}\n--- End Document ---\n\n"
"The user will give you a specific section of the document and an instruction. "
"Output ONLY the replacement text for that section. "
"If the target section starts with a markdown heading (e.g. ## Heading), "
"your output MUST also start with a heading at the same level. "
"You may revise the heading text but do not remove it. "
"Do not include other sections, explanatory text, or markdown code fences around the output. "
"Match the document's existing tone and style. "
"IMPORTANT: Preserve all markdown formatting exactly — including bullet lists (- item), "
"numbered lists (1. item), nested/indented sub-items ( - sub), bold (**text**), "
"italic (_text_), and code blocks. Never flatten nested lists into plain text."
)
user_content = (
f"--- Target Section ---\n{target_section}\n--- End Target Section ---\n\n"
f"Instruction: {instruction}"
)
if whole_doc:
system_content = (
"You are a writing assistant. Revise the document per the instruction. "
"Output ONLY the complete revised document. Preserve all structure and "
"content not addressed by the instruction. "
"Preserve all markdown formatting exactly — including bullet lists (- item), "
"numbered lists (1. item), nested/indented sub-items ( - sub), bold (**text**), "
"italic (_text_), and code blocks. Never flatten nested lists into plain text."
)
user_content = (
f"--- Document ---\n{truncated_body}\n--- End Document ---\n\n"
f"Instruction: {instruction}"
)
else:
system_content = (
"You are an AI writing assistant integrated into a note-taking app. "
"The user is editing a document. The full document is shown below for context.\n\n"
f"--- Full Document ---\n{truncated_body}\n--- End Document ---\n\n"
"The user will give you a specific section of the document and an instruction. "
"Output ONLY the replacement text for that section. "
"If the target section starts with a markdown heading (e.g. ## Heading), "
"your output MUST also start with a heading at the same level. "
"You may revise the heading text but do not remove it. "
"Do not include other sections, explanatory text, or markdown code fences around the output. "
"Match the document's existing tone and style. "
"IMPORTANT: Preserve all markdown formatting exactly — including bullet lists (- item), "
"numbered lists (1. item), nested/indented sub-items ( - sub), bold (**text**), "
"italic (_text_), and code blocks. Never flatten nested lists into plain text."
)
user_content = (
f"--- Target Section ---\n{target_section}\n--- End Target Section ---\n\n"
f"Instruction: {instruction}"
)
return [
{"role": "system", "content": system_content},
@@ -425,7 +425,7 @@ async def run_assist_generation(
await asyncio.sleep(delay)
try:
buf.content_so_far = ""
async for chunk in stream_chat(messages, model, options={"num_predict": 4096}):
async for chunk in stream_chat(messages, model, options={"num_predict": Config.OLLAMA_NUM_CTX}):
buf.content_so_far += chunk
buf.append_event("chunk", {"chunk": chunk})
@@ -0,0 +1,66 @@
from sqlalchemy import select, text
from fabledassistant.models import async_session
from fabledassistant.models.note_draft import NoteDraft
async def upsert_draft(
user_id: int,
note_id: int,
proposed_body: str,
original_body: str,
instruction: str,
scope: str,
) -> NoteDraft:
async with async_session() as session:
await session.execute(
text("""
INSERT INTO note_drafts (note_id, user_id, proposed_body, original_body, instruction, scope)
VALUES (:note_id, :user_id, :proposed_body, :original_body, :instruction, :scope)
ON CONFLICT (note_id, user_id) DO UPDATE SET
proposed_body = EXCLUDED.proposed_body,
original_body = EXCLUDED.original_body,
instruction = EXCLUDED.instruction,
scope = EXCLUDED.scope,
updated_at = NOW()
""").bindparams(
note_id=note_id,
user_id=user_id,
proposed_body=proposed_body,
original_body=original_body,
instruction=instruction,
scope=scope,
)
)
await session.commit()
result = await session.execute(
select(NoteDraft).where(
NoteDraft.note_id == note_id, NoteDraft.user_id == user_id
)
)
return result.scalars().first()
async def get_draft(user_id: int, note_id: int) -> NoteDraft | None:
async with async_session() as session:
result = await session.execute(
select(NoteDraft).where(
NoteDraft.note_id == note_id, NoteDraft.user_id == user_id
)
)
return result.scalars().first()
async def delete_draft(user_id: int, note_id: int) -> bool:
async with async_session() as session:
result = await session.execute(
select(NoteDraft).where(
NoteDraft.note_id == note_id, NoteDraft.user_id == user_id
)
)
draft = result.scalars().first()
if draft is None:
return False
await session.delete(draft)
await session.commit()
return True
@@ -0,0 +1,51 @@
from sqlalchemy import select, text
from fabledassistant.models import async_session
from fabledassistant.models.note_version import NoteVersion
MAX_VERSIONS = 20
async def create_version(user_id: int, note_id: int, body: str, title: str) -> NoteVersion:
async with async_session() as session:
version = NoteVersion(note_id=note_id, user_id=user_id, body=body, title=title)
session.add(version)
await session.commit()
await session.refresh(version)
# Prune versions beyond MAX_VERSIONS
await session.execute(
text("""
DELETE FROM note_versions
WHERE id IN (
SELECT id FROM note_versions
WHERE note_id = :note_id AND user_id = :user_id
ORDER BY created_at DESC
OFFSET :max_versions
)
""").bindparams(note_id=note_id, user_id=user_id, max_versions=MAX_VERSIONS)
)
await session.commit()
return version
async def list_versions(user_id: int, note_id: int) -> list[NoteVersion]:
async with async_session() as session:
result = await session.execute(
select(NoteVersion)
.where(NoteVersion.note_id == note_id, NoteVersion.user_id == user_id)
.order_by(NoteVersion.created_at.desc())
)
return list(result.scalars().all())
async def get_version(user_id: int, note_id: int, version_id: int) -> NoteVersion | None:
async with async_session() as session:
result = await session.execute(
select(NoteVersion).where(
NoteVersion.id == version_id,
NoteVersion.note_id == note_id,
NoteVersion.user_id == user_id,
)
)
return result.scalars().first()
+10 -1
View File
@@ -194,6 +194,9 @@ async def update_note(user_id: int, note_id: int, **fields: object) -> Note | No
note = result.scalars().first()
if note is None:
return None
# Snapshot before changes for version creation
old_body = note.body
old_title = note.title
for key, value in fields.items():
if not hasattr(note, key):
continue
@@ -207,7 +210,13 @@ async def update_note(user_id: int, note_id: int, **fields: object) -> Note | No
note.updated_at = datetime.now(timezone.utc)
await session.commit()
await session.refresh(note)
return note
# Create a version snapshot when body actually changes
if "body" in fields and fields["body"] != old_body:
from fabledassistant.services.note_versions import create_version
await create_version(user_id, note_id, old_body, old_title)
return note
async def delete_note(user_id: int, note_id: int) -> bool:
+19 -1
View File
@@ -12,7 +12,25 @@
> Include file-level details in the commit body when the change is non-trivial.
## Last Updated
2026-03-05 — Task Work Log, writing assistant improvements, task editor UI overhaul.
2026-03-05 — Note editor sidebar layout, full-document writing assist, persistent drafts, version history, context window bump.
**Note editor sidebar layout:** `NoteEditorView.vue` fully refactored into two-column layout matching `TaskEditorView`. Right sidebar (280px) contains Project, Milestone, Tags + tag suggestions, and the Writing Assistant panel (always visible, no toggle). Mobile collapses to accordion. Removed `assistOpen` ref and `✨ Assist` toggle button. `InlineAssistPanel` removed from note editor.
**Full-document writing assist:** `services/assist.py` — new `whole_doc: bool` param with a separate system prompt that instructs the model to output the complete revised document. `routes/notes.py``whole_doc` accepted from POST body; validation updated (section mode requires `target_section`, both modes require `instruction`). `composables/useAssist.ts` — added `scopeMode` ref (`'document' | 'section'`), `proposedFullBody` ref (full body after section replacement or whole-doc output), updated `diff` to always compare full document snapshots (`bodySnapshot → proposedFullBody`). Scope dropdown in sidebar drives `scopeMode` and `selectedSection`. `canSubmit` no longer requires a target in document mode. `selectSection()` and `selectTextRange()` now set `scopeMode = 'section'` automatically.
**DiffView.vue:** New standalone component (`frontend/src/components/DiffView.vue`). Full-width, flex-fills available height. Sticky summary bar (insertions / deletions count). Scrollable monospace diff body. Replaces the editor main area during review state.
**Main area state switching (NoteEditorView):** streaming → stream preview (rendered markdown); review → `DiffView` full-width; idle → normal Write/Preview/TiptapEditor.
**Persistent drafts — backend:** Migration `0022_add_note_versions_and_drafts.py``note_drafts` table (UNIQUE per `note_id + user_id`; fields: `proposed_body`, `original_body`, `instruction`, `scope`) and `note_versions` table (max 20 per note; fields: `body`, `title`, `created_at`). Models `models/note_draft.py`, `models/note_version.py`. Added imports to `models/__init__.py`. Services `services/note_drafts.py` (`upsert_draft` via INSERT … ON CONFLICT, `get_draft`, `delete_draft`) and `services/note_versions.py` (`create_version` with auto-prune to 20, `list_versions`, `get_version`). `services/notes.py` `update_note()` — snapshots old body/title before applying changes; calls `create_version` when body actually changes. Routes in `routes/notes.py`: `GET/PUT/DELETE /api/notes/<id>/draft`, `GET /api/notes/<id>/versions`, `GET /api/notes/<id>/versions/<vid>`.
**Persistent drafts — frontend:** `useAssist.ts` — accepts optional `noteId: Ref<number | null>` second param; saves draft via `PUT /api/notes/<id>/draft` after `done` event; `loadDraft(draft)` restores `bodySnapshot`, `proposedFullBody`, `instruction`, `scopeMode`, and sets state to `'review'`; `accept()` and `reject()` call `DELETE /api/notes/<id>/draft`. `NoteEditorView.vue` — on mount, after note loads, fetches draft and calls `assist.loadDraft()` if one exists. `NoteDraft` interface exported from `useAssist.ts`; `NoteDraft` + `NoteVersion` interfaces added to `frontend/src/types/task.ts`.
**Version history browser:** `HistoryPanel.vue` — wide modal (900px, 80vh), version list on left (lazy body loading), `DiffView` on right (selected version vs current body), Restore button emits body to parent. `NoteEditorView.vue` — "History" toolbar button, renders `<HistoryPanel>` with restore handler (`body = $event; markDirty()`).
**Context window + output token limits:** `OLLAMA_NUM_CTX` default raised from 16384 to 65536 in `config.py` (overridable via env var; comment updated to remove stale VRAM reference). `run_assist_generation` in `generation_task.py``num_predict` changed from hardcoded 4096 to `Config.OLLAMA_NUM_CTX`, so assist output budget always matches the configured context window.
**Previous session (2026-03-05 earlier):** Fix writing assist: disable thinking mode, drop stuck-buffer 409.
**Task Work Log (backend):** New `task_logs` table (migration `0021_add_task_logs.py`) with FK to `notes(id)` CASCADE and `users(id)` CASCADE, indexes on `task_id` and `user_id`. SQLAlchemy model `models/task_log.py`. Service `services/task_logs.py` with `create_log`, `list_logs`, `update_log` (uses `_UNSET` sentinel so `None` can explicitly clear `duration_minutes`), `delete_log` — all ownership-checked. Blueprint `routes/task_logs.py` registered in `app.py` at `/api/tasks/<task_id>/logs` (GET, POST, PATCH `/<log_id>`, DELETE `/<log_id>`). LLM tool `log_work` added to `_CORE_TOOLS` in `services/tools.py`: resolves task by title, calls `create_log`, returns `{success, log, task}`.