fix: extracted events are root entries, documents are references

- Reversed parent-child relationship: events/assessments are now root level
- Source document stored in data.source_id instead of parent_id
- Generic section summary uses section ID (e.g., '2 medications' not '2 items')
- Reprocessed Anastasiia's 62 entries
This commit is contained in:
Johan Jongsma 2026-02-02 07:22:27 +00:00
parent 8754a9df40
commit e46abbdddd
6 changed files with 344 additions and 214 deletions

View File

@ -1,7 +1,8 @@
# Inou Build System
# Run on .253: make deploy (staging), make deploy-prod (production)
# make deploy (staging @ .253), make deploy-prod (production @ .2)
VERSION := 1.0.0
STAGING_HOST := johan@192.168.1.253
PROD_HOST := johan@192.168.100.2
BUILD_TIME := $(shell date '+%Y-%m-%d %H:%M:%S')
LDFLAGS := -ldflags "-X main.Version=$(VERSION) -X 'main.BuildTime=$(BUILD_TIME)'"
@ -75,27 +76,19 @@ test:
test-rbac:
@./scripts/test-rbac.sh
# Deploy to production (builds, copies, restarts)
# Deploy to STAGING (builds locally, copies to staging, restarts)
# Runs check-db FIRST to prevent deploying code with direct DB access
deploy: check-db all $(BINDIR)/decrypt $(BINDIR)/fips-check
$(DEPLOY_DIR)/stop.sh
mkdir -p $(DEPLOY_DIR)/bin
mkdir -p $(DEPLOY_DIR)/templates
mkdir -p $(DEPLOY_DIR)/static
cp $(BINDIR)/viewer $(DEPLOY_DIR)/bin/
cp $(BINDIR)/portal $(DEPLOY_DIR)/bin/
cp $(BINDIR)/api $(DEPLOY_DIR)/bin/
cp $(BINDIR)/import-genome $(DEPLOY_DIR)/bin/
cp $(BINDIR)/import-dicom $(DEPLOY_DIR)/bin/
cp $(BINDIR)/decrypt $(DEPLOY_DIR)/bin/
cp $(BINDIR)/fips-check $(DEPLOY_DIR)/bin/
cp $(BINDIR)/lab-* $(DEPLOY_DIR)/bin/ 2>/dev/null || true
rsync -av --delete portal/templates/ $(DEPLOY_DIR)/templates/
rsync -av portal/static/ $(DEPLOY_DIR)/static/
rsync -av portal/lang/ $(DEPLOY_DIR)/lang/
$(DEPLOY_DIR)/start.sh
@echo "=== Deploying to STAGING ($(STAGING_HOST)) ==="
ssh $(STAGING_HOST) "$(DEPLOY_DIR)/stop.sh"
rsync -avz $(BINDIR)/ $(STAGING_HOST):$(DEPLOY_DIR)/bin/
rsync -avz --delete templates/ $(STAGING_HOST):$(DEPLOY_DIR)/templates/
rsync -avz static/ $(STAGING_HOST):$(DEPLOY_DIR)/static/
rsync -avz lang/ $(STAGING_HOST):$(DEPLOY_DIR)/lang/
rsync -avz api/prompts/ $(STAGING_HOST):$(DEPLOY_DIR)/prompts/
ssh $(STAGING_HOST) "$(DEPLOY_DIR)/start.sh"
@echo ""
$(DEPLOY_DIR)/status.sh
ssh $(STAGING_HOST) "$(DEPLOY_DIR)/status.sh"
# Deploy to PRODUCTION (builds locally, copies to prod, restarts)
# This is a SEPARATE action from staging deploy - requires explicit invocation

76
PROMPT-FUNCTION-BRIEF.md Normal file
View File

@ -0,0 +1,76 @@
# Prompt Function — Flagship Feature Brief
## Vision
This is one of inou's flagship features. It must be **awesome beyond belief** — pretty, intuitive, fast, useful.
User types natural language → system understands, stores, and intelligently follows up.
**Examples:**
- "I had a headache, took a Tylenol" → logs both, asks tomorrow "Did you take Tylenol?"
- "Blood pressure 120/80" → stores with proper fields (systolic/diastolic)
- "Leg trainer: 3 sets, 12 reps, 45kg" → handles complex multi-parameter input
- "My period stopped" → does NOT ask about period the next day
- "I'm pregnant" then later "I had my period" → handles contradiction intelligently
## Core Concept
Everything displays as a **prompt card**. The card's state changes:
- **Due** — waiting for input
- **Completed** — what you just told us (confirmation)
- **Pending** — coming tomorrow
When you type freeform input, you immediately see it as a completed card. Tomorrow's follow-up appears as a due card.
## Smart & Sensitive
The system must be intelligent about follow-ups:
- One-time events don't generate recurring prompts
- Contradictions are handled (pregnancy → period means pregnancy ended)
- "Stopped taking X" dismisses the X prompt
- Context matters — understand what makes sense to ask again
## Design
Follow the styleguide: `inou.com/styleguide`
Cards are not in the styleguide yet — design freedom here, but match the inou aesthetic.
## Existing Code
**LLM Pipeline:**
- `api/prompts/triage.md` — categorizes input
- `api/prompts/*.md` — category-specific extraction prompts
- `api/api_llm.go``callLLMForPrompt()` orchestrates triage → extraction
- `api/api_prompts.go` — API endpoints, `tryGeneratePromptFromFreeform()`
**Data:**
- `lib/types.go``Prompt`, `Entry` structs
- `lib/prompt.go` — CRUD, respond, skip, dismiss
**UI:**
- `portal/prompts.go` — current prompts page
- `portal/templates/prompts.tmpl` — current template
**Test harness:**
- `test-prompts/main.go` — CLI tool: `./test-prompts "I took aspirin"`
## Flexibility
Input configs must handle:
- Single checkbox ("Did you take X?")
- Multiple checkboxes ("Morning pills: ☐ Lisinopril ☐ Metformin")
- Numeric with units ("Weight: ___ kg")
- Multi-field ("BP: ___/___ mmHg")
- Complex forms ("Leg trainer: sets ___ reps ___ weight ___")
- Scales ("Pain level 1-10")
The LLM extraction prompts define `input_config` — the UI renders whatever structure it returns.
## Must Have
- Edit recognized prompts (change question, schedule, fields)
- Delete/dismiss prompts
- Works beautifully on web and mobile (WebView)
- Fast — no jarring waits after input
- Immediate visual confirmation of what was captured

View File

@ -124,17 +124,18 @@ func createEventEntry(sourceID string, event map[string]interface{}) error {
}
}
// Build data
// Build data - include source document as reference (not parent)
data := map[string]interface{}{
"where": where,
"details": details,
"where": where,
"details": details,
"source_id": sourceID, // reference to source document
}
dataJSON, _ := json.Marshal(data)
entry := lib.Entry{
EntryID: lib.NewID(),
DossierID: dossierID,
ParentID: sourceID, // link to source document
ParentID: "", // ROOT level - event is the primary entity
Category: category,
Type: eventType,
Value: what,
@ -150,15 +151,17 @@ func createAssessmentEntry(sourceID string, assessment map[string]interface{}) e
by, _ := assessment["by"].(string)
states, _ := assessment["states"].(string)
// Include source document as reference (not parent)
data := map[string]interface{}{
"provider": by,
"provider": by,
"source_id": sourceID, // reference to source document
}
dataJSON, _ := json.Marshal(data)
entry := lib.Entry{
EntryID: lib.NewID(),
DossierID: dossierID,
ParentID: sourceID, // link to source document
ParentID: "", // ROOT level - assessment is the primary entity
Category: lib.CategoryAssessment,
Type: "clinical_opinion",
Value: states,

View File

@ -178,7 +178,8 @@ func BuildDossierSections(targetID, targetHex string, target *lib.Dossier, p *li
if cfg.Category > 0 {
entries, _ := lib.EntryList(nil, "", cfg.Category, &lib.EntryFilter{DossierID: targetID, Limit: 50})
section.Items = entriesToSectionItems(entries)
section.Summary = fmt.Sprintf("%d items", len(entries))
// Use section ID for summary (e.g., "2 medications" not "2 items")
section.Summary = fmt.Sprintf("%d %s", len(entries), cfg.ID)
}
}

View File

@ -242,9 +242,19 @@ func handlePrompts(w http.ResponseWriter, r *http.Request) {
entries = append(entries, ev)
}
// Split prompts into due and upcoming
var duePrompts, upcomingPrompts []PromptView
for _, p := range prompts {
if p.IsDue || p.IsFreeform {
duePrompts = append(duePrompts, p)
} else {
upcomingPrompts = append(upcomingPrompts, p)
}
}
// Count due items (excluding freeform)
dueCount := 0
for _, p := range prompts {
for _, p := range duePrompts {
if !p.IsFreeform {
dueCount++
}
@ -254,11 +264,12 @@ func handlePrompts(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
templates.ExecuteTemplate(w, "base.tmpl", struct {
PageData
Prompts []PromptView
Entries []EntryView
TargetHex string
DueCount int
}{data, prompts, entries, targetHex, dueCount})
DuePrompts []PromptView
UpcomingPrompts []PromptView
Entries []EntryView
TargetHex string
DueCount int
}{data, duePrompts, upcomingPrompts, entries, targetHex, dueCount})
}
func handlePromptRespond(w http.ResponseWriter, r *http.Request) {

View File

@ -1,14 +1,19 @@
{{define "prompts"}}
<div class="sg-container">
<h1 style="font-size: 2.5rem; font-weight: 700;">{{if .TargetDossier}}{{.TargetDossier.Name}}'s {{end}}Daily Check-in</h1>
<h1 style="font-size: 2.5rem; font-weight: 700;">Daily Check-in</h1>
<p class="intro" style="font-size: 1.15rem; font-weight: 300; line-height: 1.8;">Track daily measurements and observations</p>
{{if .Error}}<div class="msg msg-error">{{.Error}}</div>{{end}}
{{if .Success}}<div class="msg msg-success">{{.Success}}</div>{{end}}
{{if .Prompts}}
<!-- Processing Toast -->
<div id="processing-toast" class="processing-toast">
<div class="processing-spinner"></div>
<span id="processing-text">Processing...</span>
</div>
<!-- TODAY Section -->
<div class="data-card">
<!-- Section header -->
<div class="prompt-section-header">
<div class="prompt-section-bar"></div>
<div class="prompt-section-info">
@ -17,7 +22,8 @@
</div>
</div>
<div class="prompt-list">
<div class="prompt-list" id="today-list">
<!-- Entries (readonly) -->
{{range .Entries}}
<div class="prompt-item entry-item" data-entry-id="{{.ID}}">
<a href="#" class="prompt-dismiss" onclick="deleteEntry('{{.ID}}'); return false;" title="Delete">✕</a>
@ -46,10 +52,10 @@
{{if .SourceInput}}<div class="prompt-source">↳ "{{.SourceInput}}"</div>{{end}}
</div>
{{end}}
{{range .Prompts}}
{{$prompt := .}}
<div class="prompt-item{{if not .IsDue}} prompt-item-future{{end}}" data-prompt-id="{{.ID}}">
<!-- Dismiss button -->
<!-- Due Prompts (interactive) -->
{{range .DuePrompts}}
<div class="prompt-item" data-prompt-id="{{.ID}}">
<a href="#" class="prompt-dismiss" onclick="showDismissConfirm(this, '{{.ID}}'); return false;" title="Don't ask again">✕</a>
<div class="dismiss-confirm">
<span>Stop tracking?</span>
@ -57,8 +63,8 @@
<a href="#" onclick="hideDismissConfirm(this); return false;">No</a>
</div>
<!-- Saved state (only show if due AND has response) -->
<div class="prompt-saved" style="display: {{if and .HasResponse .IsDue}}block{{else}}none{{end}};">
<!-- Saved state -->
<div class="prompt-saved" style="display: {{if .HasResponse}}block{{else}}none{{end}};">
<div class="prompt-saved-header">
<span class="prompt-question">{{.Question}}</span>
<span class="prompt-saved-value">{{.LastResponseRaw}}</span>
@ -70,8 +76,8 @@
{{if .SourceInput}}<div class="prompt-source">↳ "{{.SourceInput}}"</div>{{end}}
</div>
<!-- Input state (show if not due, OR if due but no response) -->
<form class="prompt-form" data-prompt-id="{{.ID}}"{{if and .HasResponse .IsDue}} style="display: none;"{{end}}>
<!-- Input form -->
<form class="prompt-form" data-prompt-id="{{.ID}}" data-is-freeform="{{.IsFreeform}}"{{if .HasResponse}} style="display: none;"{{end}}>
<div class="prompt-header">
<span class="prompt-question">{{.Question}}</span>
{{if .IsFreeform}}<span class="prompt-due">optional</span>{{else if .NextAsk}}<span class="prompt-due{{if .IsOverdue}} prompt-overdue{{end}}">{{.NextAskFormatted}}</span>{{end}}
@ -161,7 +167,10 @@
{{end}}
{{end}}
{{else}}
<textarea name="response_raw" class="prompt-textarea" rows="3" placeholder="Type your notes..."></textarea>
<div class="freeform-input-row">
<textarea name="response_raw" class="prompt-textarea" rows="2" placeholder="Type anything... (press Enter to submit)"></textarea>
<button type="button" class="freeform-submit-btn" onclick="submitFreeform(this)">→</button>
</div>
{{end}}
</div>
</form>
@ -169,10 +178,40 @@
{{end}}
</div>
</div>
{{else}}
<div class="empty-state">
<p>All caught up! No items due right now.</p>
<a href="/dossier/{{.TargetHex}}/prompts?all=1" class="btn btn-secondary">View all items</a>
<!-- UPCOMING Section -->
{{if .UpcomingPrompts}}
<div class="data-card" style="margin-top: 24px;">
<div class="prompt-section-header">
<div class="prompt-section-bar" style="background: var(--text-muted);"></div>
<div class="prompt-section-info">
<div class="prompt-section-title">UPCOMING</div>
<div class="prompt-section-subtitle">{{len .UpcomingPrompts}} scheduled</div>
</div>
</div>
<div class="prompt-list">
{{range .UpcomingPrompts}}
<div class="prompt-item prompt-item-upcoming" data-prompt-id="{{.ID}}">
<a href="#" class="prompt-dismiss" onclick="showDismissConfirm(this, '{{.ID}}'); return false;" title="Don't ask again">✕</a>
<div class="dismiss-confirm">
<span>Stop tracking?</span>
<a href="#" onclick="confirmDismiss('{{.ID}}'); return false;">Yes</a>
<a href="#" onclick="hideDismissConfirm(this); return false;">No</a>
</div>
<div class="prompt-header">
<span class="prompt-question">{{.Question}}</span>
<span class="prompt-due">{{.NextAskFormatted}}</span>
</div>
{{if .LastResponseRaw}}
<div class="prompt-body">
<span class="prompt-last-value">Last: {{.LastResponseRaw}}</span>
</div>
{{end}}
{{if .SourceInput}}<div class="prompt-source">↳ "{{.SourceInput}}"</div>{{end}}
</div>
{{end}}
</div>
</div>
{{end}}
@ -184,10 +223,60 @@
</div>
<style>
.page-subtitle {
font-size: 1rem;
color: var(--text-muted);
margin-top: 4px;
.processing-toast {
display: none;
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
background: var(--text);
color: white;
padding: 12px 24px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
z-index: 1000;
align-items: center;
gap: 12px;
}
.processing-toast.show {
display: flex;
animation: toastIn 0.2s ease-out;
}
@keyframes toastIn {
from { opacity: 0; transform: translateX(-50%) translateY(-10px); }
to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
.processing-spinner {
width: 18px;
height: 18px;
border: 2px solid rgba(255,255,255,0.3);
border-top-color: white;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.freeform-input-row {
display: flex;
gap: 8px;
align-items: flex-start;
}
.freeform-input-row .prompt-textarea {
flex: 1;
}
.freeform-submit-btn {
padding: 8px 16px;
background: var(--accent);
color: white;
border: none;
border-radius: 6px;
font-size: 1.1rem;
cursor: pointer;
transition: background 0.15s;
}
.freeform-submit-btn:hover {
background: #9a4408;
}
.prompt-section-header {
display: flex;
@ -223,15 +312,13 @@
.prompt-item:last-child {
border-bottom: none;
}
.prompt-item-future {
opacity: 0.5;
.prompt-item-upcoming {
opacity: 0.6;
background: #fafafa;
}
.prompt-item-future .prompt-question::after {
content: ' (scheduled)';
font-size: 0.75rem;
color: #999;
font-weight: normal;
.prompt-last-value {
font-size: 0.9rem;
color: var(--text-muted);
}
.prompt-dismiss {
position: absolute;
@ -294,11 +381,6 @@
align-items: flex-end;
gap: 8px;
}
.prompt-field-group {
display: flex;
flex-direction: column;
gap: 4px;
}
.prompt-field-row {
display: flex;
align-items: center;
@ -355,11 +437,6 @@
font-size: 0.875rem;
color: var(--text-muted);
}
.prompt-separator {
font-size: 1.1rem;
color: var(--text-muted);
margin-bottom: 8px;
}
.prompt-checkbox {
display: flex;
align-items: center;
@ -430,10 +507,6 @@
border-color: var(--accent);
color: white;
}
.prompt-scale-btn:focus {
outline: none;
box-shadow: 0 0 0 2px rgba(198, 93, 7, 0.2);
}
.prompt-select {
padding: 8px 12px;
border: 1px solid #ddd;
@ -453,7 +526,7 @@
display: flex;
justify-content: space-between;
align-items: flex-start;
padding-right: 40px; /* space for dismiss X */
padding-right: 40px;
gap: 20px;
}
.prompt-saved-value {
@ -502,54 +575,68 @@
font-weight: 600;
color: var(--accent);
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
<script>
const targetHex = '{{.TargetHex}}';
document.querySelectorAll('.prompt-item').forEach(item => {
item.addEventListener('focusout', (e) => {
setTimeout(() => {
if (!item.contains(document.activeElement)) {
saveItem(item);
}
}, 100);
});
// Processing toast
function showProcessing(text) {
const toast = document.getElementById('processing-toast');
document.getElementById('processing-text').textContent = text || 'Processing...';
toast.classList.add('show');
}
function hideProcessing() {
document.getElementById('processing-toast').classList.remove('show');
}
// Initialize all prompt items
document.querySelectorAll('.prompt-item').forEach(item => {
const form = item.querySelector('.prompt-form');
if (!form) return;
// Handle blur for non-freeform
if (form.dataset.isFreeform !== 'true') {
item.addEventListener('focusout', (e) => {
setTimeout(() => {
if (!item.contains(document.activeElement)) {
saveItem(item);
}
}, 100);
});
}
// Checkbox auto-save
item.querySelectorAll('input[type=checkbox]').forEach(cb => {
cb.addEventListener('change', () => saveItem(item));
});
// Scale buttons
item.querySelectorAll('.prompt-scale-btn').forEach(btn => {
btn.addEventListener('click', () => {
const field = btn.dataset.field;
const value = btn.dataset.value;
// Deselect siblings
btn.parentElement.querySelectorAll('.prompt-scale-btn').forEach(b => b.classList.remove('selected'));
// Select this one
btn.classList.add('selected');
// Update hidden input
const hidden = item.querySelector('input[name="field_' + field + '"]');
if (hidden) hidden.value = value;
// Auto-save
const hidden = item.querySelector('input[name="field_' + btn.dataset.field + '"]');
if (hidden) hidden.value = btn.dataset.value;
saveItem(item);
});
});
// Select auto-save
item.querySelectorAll('.prompt-select').forEach(sel => {
sel.addEventListener('change', () => saveItem(item));
});
// Freeform Enter key
const textarea = item.querySelector('.prompt-textarea');
if (textarea && form.dataset.isFreeform === 'true') {
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
submitFreeform(textarea);
}
});
}
});
function showDismissConfirm(btn, promptId) {
@ -578,11 +665,9 @@ async function confirmDismiss(promptId) {
}
async function deleteEntry(entryId) {
if (!confirm('Delete this entry and stop future tracking?')) return;
if (!confirm('Delete this entry?')) return;
try {
await fetch('/dossier/' + targetHex + '/entries/' + entryId, {
method: 'DELETE'
});
await fetch('/dossier/' + targetHex + '/entries/' + entryId, { method: 'DELETE' });
document.querySelector('.entry-item[data-entry-id="' + entryId + '"]').style.display = 'none';
} catch (err) {
console.error('Delete failed:', err);
@ -590,7 +675,6 @@ async function deleteEntry(entryId) {
}
function editEntry(btn) {
// TODO: implement entry editing
alert('Entry editing coming soon');
}
@ -601,102 +685,58 @@ function editPrompt(btn) {
item.querySelector('.prompt-form input:not([type=hidden]), .prompt-form textarea')?.focus();
}
function addNewPromptCard(prompt) {
const container = document.querySelector('.prompts-section');
if (!container) return;
async function submitFreeform(el) {
const item = el.closest('.prompt-item');
const form = item.querySelector('.prompt-form');
const textarea = form.querySelector('textarea[name="response_raw"]');
const value = textarea.value.trim();
const hasResponse = prompt.last_response_raw || prompt.last_response;
const isDue = prompt.is_due !== false;
const futureClass = isDue ? '' : ' prompt-item-future';
if (!value) return;
// Build input fields HTML based on input_config
let fieldsHtml = '';
if (prompt.input_config && prompt.input_config.fields) {
prompt.input_config.fields.forEach(field => {
if (field.type === 'checkbox') {
fieldsHtml += `
<label class="prompt-checkbox">
<input type="checkbox" name="field_${field.key}" value="1">
<span class="prompt-checkbox-box"></span>
</label>`;
} else if (field.type === 'number') {
const step = field.step || (field.datatype === 'float' ? '0.1' : '1');
const min = field.min !== undefined ? `min="${field.min}"` : '';
const max = field.max !== undefined ? `max="${field.max}"` : '';
const unit = field.unit ? `<span class="prompt-unit">${field.unit}</span>` : '';
fieldsHtml += `
<input type="number" name="field_${field.key}"
placeholder="${field.label || ''}"
step="${step}" ${min} ${max}
class="prompt-input prompt-input-number">
${unit}`;
} else {
fieldsHtml += `
<input type="text" name="field_${field.key}"
placeholder="${field.label || ''}"
class="prompt-input">`;
}
showProcessing('Processing "' + value.substring(0, 30) + (value.length > 30 ? '...' : '') + '"');
try {
const res = await fetch('/dossier/' + targetHex + '/prompts/respond', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
body: new URLSearchParams({
prompt_id: form.dataset.promptId,
action: 'respond',
response: '{}',
response_raw: value
})
});
} else if (prompt.input_type === 'freeform') {
fieldsHtml = `<textarea name="response_raw" class="prompt-textarea" placeholder="Type here..."></textarea>`;
}
const savedValue = prompt.last_response_raw || '';
const formDisplay = hasResponse ? 'none' : 'block';
const savedDisplay = hasResponse ? 'block' : 'none';
if (res.ok) {
const data = await res.json();
textarea.value = '';
const cardHtml = `
<div class="prompt-item prompt-item-new${futureClass}" style="animation: slideIn 0.3s ease-out;">
<a href="#" class="prompt-dismiss" onclick="showDismissConfirm(this, '${prompt.id}'); return false;" title="Don't ask again">✕</a>
<div class="dismiss-confirm">
<span>Stop tracking?</span>
<a href="#" onclick="confirmDismiss('${prompt.id}'); return false;">Yes</a>
<a href="#" onclick="hideDismissConfirm(this); return false;">No</a>
</div>
<div class="prompt-saved" style="display: ${savedDisplay};">
<div class="prompt-saved-header">
<span class="prompt-question">${prompt.question}</span>
<span class="prompt-saved-value">${savedValue}</span>
</div>
<div class="prompt-saved-footer">
<span class="prompt-saved-time">just now</span>
<a href="#" class="prompt-edit" onclick="editPrompt(this); return false;">edit</a>
</div>
</div>
<form class="prompt-form" data-prompt-id="${prompt.id}" style="display: ${formDisplay};">
<div class="prompt-header">
<span class="prompt-question">${prompt.question}</span>
<span class="prompt-due">${isDue ? 'now' : 'tomorrow'}</span>
</div>
<div class="prompt-fields">
${fieldsHtml}
</div>
</form>
</div>`;
hideProcessing();
// Insert after the header
const header = container.querySelector('.section-header');
if (header) {
header.insertAdjacentHTML('afterend', cardHtml);
} else {
container.insertAdjacentHTML('afterbegin', cardHtml);
}
// Attach blur handler to new inputs
const newCard = container.querySelector('.prompt-item-new');
if (newCard) {
newCard.classList.remove('prompt-item-new');
if (!hasResponse) {
newCard.querySelectorAll('input, textarea').forEach(input => {
input.addEventListener('blur', () => setTimeout(() => saveItem(newCard), 100));
});
newCard.querySelector('input, textarea')?.focus();
// Show success briefly then reload
if (data.new_prompt) {
showProcessing('Created: ' + data.new_prompt.question);
setTimeout(() => {
hideProcessing();
window.location.reload();
}, 1500);
}
} else {
hideProcessing();
}
} catch (err) {
console.error('Submit failed:', err);
hideProcessing();
}
}
async function saveItem(item) {
const form = item.querySelector('.prompt-form');
if (!form) return;
const promptId = form.dataset.promptId;
const inputs = form.querySelectorAll('input:not([type=hidden]), textarea');
@ -722,6 +762,17 @@ async function saveItem(item) {
}
});
// Also check hidden inputs for scale values
form.querySelectorAll('input[type=hidden]').forEach(hidden => {
if (hidden.value) {
const key = hidden.name.replace('field_', '');
response[key] = hidden.value;
hasValue = true;
displayValue += (displayValue ? ' / ' : '') + hidden.value;
responseRaw += (responseRaw ? ' / ' : '') + hidden.value;
}
});
if (!hasValue) return;
try {
@ -740,16 +791,11 @@ async function saveItem(item) {
});
if (res.ok) {
const data = await res.json();
form.style.display = 'none';
const saved = item.querySelector('.prompt-saved');
saved.querySelector('.prompt-saved-value').textContent = displayValue;
saved.style.display = 'block';
// If LLM generated a new prompt, add it to the deck
if (data.new_prompt) {
addNewPromptCard(data.new_prompt);
if (saved) {
saved.querySelector('.prompt-saved-value').textContent = displayValue;
saved.style.display = 'block';
}
}
} catch (err) {