Merge pull request 'feat: frictionless incident capture' (#13) from feat/frictionless-capture into main

This commit is contained in:
pyr0ball 2026-05-11 09:53:25 -07:00
commit e1abc1e73d
14 changed files with 960 additions and 334 deletions

2
.gitignore vendored
View file

@ -12,3 +12,5 @@ __pycache__/
.turnstone-api.pid
web/node_modules/
web/dist/
.superpowers/
.worktrees/

View file

@ -39,8 +39,10 @@ from app.services.search import (
stats_summary as _stats,
format_results,
)
from app.services.diagnose import diagnose as _diagnose
DB_PATH = Path(os.environ.get("TURNSTONE_DB", Path(__file__).parent.parent / "data" / "turnstone.db"))
PREFS_PATH = DB_PATH.parent / "preferences.json"
DIST_DIR = Path(__file__).parent.parent / "web" / "dist"
SOURCE_HOST = os.environ.get("TURNSTONE_SOURCE_HOST", "unknown")
BUNDLE_ENDPOINT = os.environ.get("TURNSTONE_BUNDLE_ENDPOINT", "")
@ -50,7 +52,7 @@ app = FastAPI(title="Turnstone API", version="0.1.0", docs_url="/turnstone/docs"
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["GET", "POST", "DELETE"],
allow_methods=["GET", "POST", "DELETE", "PATCH"],
allow_headers=["*"],
)
@ -60,6 +62,29 @@ def _startup() -> None:
ensure_schema(DB_PATH)
def _load_prefs() -> dict[str, str]:
if PREFS_PATH.exists():
try:
return json.loads(PREFS_PATH.read_text())
except (json.JSONDecodeError, OSError):
pass
return {"entry_point_style": "topbar"}
def _save_prefs(data: dict[str, str]) -> None:
PREFS_PATH.write_text(json.dumps(data))
class DiagnoseRequest(BaseModel):
query: str
since: str | None = None
until: str | None = None
class SettingsBody(BaseModel):
entry_point_style: str
class IncidentCreate(BaseModel):
label: str
issue_type: str = ""
@ -167,6 +192,38 @@ def diagnose(
}
@router.post("/api/diagnose")
def diagnose_post(body: DiagnoseRequest) -> dict:
if not body.query.strip():
return {
"summary": {
"total": 0, "window_start": None, "window_end": None,
"time_detected": False, "by_severity": {}, "by_source": {},
},
"entries": [],
}
result = _diagnose(DB_PATH, query=body.query, since=body.since, until=body.until)
return {
"summary": result["summary"],
"entries": [dataclasses.asdict(r) for r in result["entries"]],
}
@router.get("/api/settings")
def get_settings() -> dict:
return _load_prefs()
@router.patch("/api/settings")
def patch_settings(body: SettingsBody) -> dict:
if body.entry_point_style not in ("topbar", "fab"):
raise HTTPException(status_code=422, detail="entry_point_style must be 'topbar' or 'fab'")
prefs = _load_prefs()
prefs["entry_point_style"] = body.entry_point_style
_save_prefs(prefs)
return prefs
@router.get("/api/sources")
def list_sources() -> dict:
return {"sources": _list_sources(DB_PATH)}

100
app/services/diagnose.py Normal file
View file

@ -0,0 +1,100 @@
"""Frictionless diagnose service — NL time extraction + layered log search."""
from __future__ import annotations
import logging
import re
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from app.services.search import SearchResult, entries_in_window, search
logger = logging.getLogger(__name__)
try:
from dateparser.search import search_dates as _search_dates # type: ignore[import]
_HAS_DATEPARSER = True
except ImportError:
_search_dates = None # type: ignore[assignment]
_HAS_DATEPARSER = False
def parse_time_window(query: str) -> tuple[str | None, str | None, str]:
"""Extract a time window from a natural-language query string.
Returns (since_iso, until_iso, keywords) where keywords is the query with
the matched time phrase stripped. Falls back to last-60-min window.
"""
if _HAS_DATEPARSER and _search_dates is not None:
try:
results = _search_dates(query, languages=["en"], settings={"PREFER_DATES_FROM": "past"})
except Exception:
logger.warning("dateparser failed on query %r — falling back to 60-min window", query)
results = None
if results:
phrase, dt = results[0]
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
since = (dt - timedelta(minutes=30)).isoformat()
until = (dt + timedelta(minutes=30)).isoformat()
keywords = re.sub(r"\s{2,}", " ", query.replace(phrase, " ").strip())
return since, until, keywords or query
return _last_n_minutes(60), _now_iso(), query
def diagnose(
db_path: Path,
query: str,
since: str | None = None,
until: str | None = None,
) -> dict[str, Any]:
"""Run layered log search with NL time extraction. Returns summary + entries."""
time_detected = since is not None and until is not None
if not time_detected:
parsed_since, parsed_until, keywords = parse_time_window(query)
since = since or parsed_since
until = until or parsed_until
time_detected = keywords != query
else:
keywords = query
keyword_hits = search(db_path, query=keywords, since=since, until=until, limit=150, or_mode=True)
window_hits = entries_in_window(db_path, since=since, until=until, limit=50)
seen: set[str] = set()
merged: list[SearchResult] = []
for r in keyword_hits + window_hits:
if r.entry_id not in seen:
seen.add(r.entry_id)
merged.append(r)
combined = sorted(merged, key=lambda r: (r.timestamp_iso or "\xff", r.sequence))[:200]
by_severity: dict[str, int] = {"CRITICAL": 0, "ERROR": 0, "WARN": 0, "INFO": 0}
by_source: dict[str, int] = {}
for r in combined:
sev = (r.severity or "INFO").upper()
if sev in by_severity:
by_severity[sev] += 1
by_source[r.source_id] = by_source.get(r.source_id, 0) + 1
return {
"summary": {
"total": len(combined),
"window_start": since,
"window_end": until,
"time_detected": time_detected,
"by_severity": by_severity,
"by_source": by_source,
},
"entries": combined,
}
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _last_n_minutes(n: int) -> str:
return (datetime.now(timezone.utc) - timedelta(minutes=n)).isoformat()

View file

@ -4,3 +4,4 @@ pydantic>=2.0.0
pyyaml>=6.0
aiofiles>=23.0.0
python-multipart>=0.0.9
dateparser>=1.2.0

View file

@ -0,0 +1,63 @@
"""Tests for app/services/diagnose.py — parse_time_window."""
from __future__ import annotations
from datetime import datetime, timezone
from unittest.mock import patch
from app.services.diagnose import diagnose, parse_time_window
def test_no_time_phrase_falls_back_to_last_60_min():
with patch("app.services.diagnose._HAS_DATEPARSER", True), \
patch("app.services.diagnose._search_dates", return_value=None):
since, until, keywords = parse_time_window("plex stopped playing audio")
assert since is not None and until is not None
assert keywords == "plex stopped playing audio"
diff = (datetime.fromisoformat(until) - datetime.fromisoformat(since)).total_seconds()
assert abs(diff - 3600) < 5
def test_time_phrase_detected_produces_60min_window():
dt = datetime(2026, 5, 11, 14, 0, tzinfo=timezone.utc)
with patch("app.services.diagnose._HAS_DATEPARSER", True), \
patch("app.services.diagnose._search_dates", return_value=[("around 2pm", dt)]):
since, until, keywords = parse_time_window("plex stopped audio around 2pm")
diff = (datetime.fromisoformat(until) - datetime.fromisoformat(since)).total_seconds()
assert abs(diff - 3600) < 5
def test_time_phrase_stripped_from_keywords():
dt = datetime(2026, 5, 11, 14, 0, tzinfo=timezone.utc)
with patch("app.services.diagnose._HAS_DATEPARSER", True), \
patch("app.services.diagnose._search_dates", return_value=[("around 2pm", dt)]):
_, _, keywords = parse_time_window("plex stopped audio around 2pm")
assert "around 2pm" not in keywords
assert "plex" in keywords
def test_no_dateparser_falls_back_to_60min():
with patch("app.services.diagnose._HAS_DATEPARSER", False), \
patch("app.services.diagnose._search_dates", None):
since, until, keywords = parse_time_window("plex stopped playing audio")
assert keywords == "plex stopped playing audio"
diff = (datetime.fromisoformat(until) - datetime.fromisoformat(since)).total_seconds()
assert abs(diff - 3600) < 5
def test_keywords_cleaned_of_extra_spaces():
dt = datetime(2026, 5, 11, 14, 0, tzinfo=timezone.utc)
with patch("app.services.diagnose._HAS_DATEPARSER", True), \
patch("app.services.diagnose._search_dates", return_value=[("around 2pm", dt)]):
_, _, keywords = parse_time_window("plex stopped audio around 2pm extra")
assert " " not in keywords
def test_diagnose_with_explicit_window_sets_time_detected(tmp_path):
from app.ingest.pipeline import ensure_schema
db = tmp_path / "test.db"
ensure_schema(db)
result = diagnose(db, query="plex", since="2026-05-11T14:00:00+00:00", until="2026-05-11T15:00:00+00:00")
assert result["summary"]["time_detected"] is True
assert result["summary"]["total"] == 0 # empty DB
assert result["summary"]["window_start"] == "2026-05-11T14:00:00+00:00"

View file

@ -12,11 +12,15 @@
:to="link.to"
class="px-3 py-1 rounded text-sm text-text-muted hover:text-text-primary hover:bg-surface-raised transition-colors"
active-class="text-accent bg-accent-muted"
>
{{ link.label }}
</RouterLink>
>{{ link.label }}</RouterLink>
</div>
<div class="ml-auto flex items-center gap-3">
<RouterLink
to="/settings"
class="text-text-dim hover:text-text-primary transition-colors leading-none"
title="Settings"
aria-label="Settings"
></RouterLink>
<button
@click="toggleTheme"
:title="isDark ? 'Switch to light mode' : 'Switch to dark mode'"
@ -26,14 +30,25 @@
<StatusDot />
</div>
</nav>
<!-- Persistent quick-capture bar (topbar mode) -->
<QuickCaptureBar v-if="entryPointStyle === 'topbar'" />
<RouterView />
<!-- FAB entry point (fab mode) -->
<QuickCaptureFab v-if="entryPointStyle === 'fab'" />
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ref, onMounted } from 'vue'
import { RouterLink, RouterView } from 'vue-router'
import StatusDot from '@/components/StatusDot.vue'
import QuickCaptureBar from '@/components/QuickCaptureBar.vue'
import QuickCaptureFab from '@/components/QuickCaptureFab.vue'
const BASE = import.meta.env.BASE_URL.replace(/\/$/, '')
const navLinks = [
{ to: '/dashboard', label: 'Dashboard' },
@ -45,10 +60,21 @@ const navLinks = [
]
const isDark = ref(document.documentElement.classList.contains('dark'))
const entryPointStyle = ref<'topbar' | 'fab'>('topbar')
function toggleTheme() {
isDark.value = !isDark.value
document.documentElement.classList.toggle('dark', isDark.value)
localStorage.setItem('ts-theme', isDark.value ? 'dark' : 'light')
}
onMounted(async () => {
try {
const res = await fetch(`${BASE}/api/settings`)
if (res.ok) {
const data = await res.json()
entryPointStyle.value = data.entry_point_style ?? 'topbar'
}
} catch { /* default to topbar */ }
})
</script>

View file

@ -0,0 +1,222 @@
<template>
<div class="rounded border border-surface-border bg-surface-raised p-5">
<h2 class="text-text-primary text-sm font-semibold mb-4 uppercase tracking-wider">Tag New Incident</h2>
<div class="space-y-4">
<!-- Label -->
<div>
<label class="block text-xs text-text-dim mb-1">Description <span class="text-accent">*</span></label>
<input
v-model="form.label"
type="text"
placeholder='e.g. "plex stopped playing audio" or "bluetooth kept disconnecting"'
class="w-full bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent"
/>
<p class="text-text-dim text-xs mt-1">Your literal description used to find relevant log entries in the window.</p>
</div>
<!-- Time bucket picker -->
<div>
<label class="block text-xs text-text-dim mb-2">When did it happen?</label>
<div class="flex flex-wrap gap-2 mb-3">
<button
v-for="preset in presets"
:key="preset.key"
@click="applyPreset(preset.key)"
:class="[
'px-3 py-1.5 rounded text-xs border transition-colors',
activePreset === preset.key
? 'bg-accent text-surface border-accent'
: 'bg-surface border-surface-border text-text-muted hover:text-text-primary hover:border-accent'
]"
>{{ preset.label }}</button>
<button
@click="toggleCustomPicker"
:class="[
'px-3 py-1.5 rounded text-xs border transition-colors',
showCustomPicker
? 'bg-accent text-surface border-accent'
: 'bg-surface border-surface-border text-text-muted hover:text-text-primary hover:border-accent'
]"
>Custom range</button>
</div>
<div v-if="showCustomPicker" class="flex flex-wrap gap-3 mt-2">
<div>
<label class="block text-xs text-text-dim mb-1">Start</label>
<input
v-model="form.started_at_local"
type="datetime-local"
class="bg-surface border border-surface-border rounded px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:border-accent"
@change="activePreset = 'custom'"
/>
</div>
<div>
<label class="block text-xs text-text-dim mb-1">End <span class="text-text-dim">(leave blank if ongoing)</span></label>
<input
v-model="form.ended_at_local"
type="datetime-local"
class="bg-surface border border-surface-border rounded px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:border-accent"
@change="activePreset = 'custom'"
/>
</div>
</div>
<p v-if="windowSummary" class="text-text-dim text-xs mt-2">
Window: <span class="text-text-muted">{{ windowSummary }}</span>
</p>
</div>
<!-- Issue type -->
<div>
<label class="block text-xs text-text-dim mb-1">Issue type <span class="text-text-dim">(optional)</span></label>
<input
v-model="form.issue_type"
type="text"
list="issue-type-suggestions"
placeholder='e.g. "qbit_stall", "auth_failure", "disk_full"'
class="w-full bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent font-mono"
/>
<datalist id="issue-type-suggestions">
<option value="qbit_stall" /><option value="qbit_crash" /><option value="auth_failure" />
<option value="disk_full" /><option value="network_drop" /><option value="service_crash" />
<option value="permission_error" /><option value="oom" />
</datalist>
</div>
<!-- Severity + Notes -->
<div class="flex flex-wrap gap-4">
<div>
<label class="block text-xs text-text-dim mb-1">Severity</label>
<select
v-model="form.severity"
class="bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary focus:outline-none focus:border-accent"
>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
<option value="critical">Critical</option>
</select>
</div>
<div class="flex-1 min-w-48">
<label class="block text-xs text-text-dim mb-1">Notes <span class="text-text-dim">(optional)</span></label>
<input
v-model="form.notes"
type="text"
placeholder="Any extra context…"
class="w-full bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent"
/>
</div>
</div>
<!-- Submit -->
<div class="flex items-center gap-3">
<button
@click="submit"
:disabled="!form.label.trim() || submitting"
class="px-4 py-2 bg-accent text-surface text-sm rounded font-medium hover:opacity-90 transition-opacity disabled:opacity-40 disabled:cursor-not-allowed"
>
{{ submitting ? 'Tagging…' : 'Tag Incident' }}
</button>
<span v-if="submitError" class="text-sev-error text-xs">{{ submitError }}</span>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
const BASE = import.meta.env.BASE_URL.replace(/\/$/, '')
const emit = defineEmits<{ created: [label: string] }>()
const presets = [
{ key: 'ongoing', label: 'Ongoing' },
{ key: 'just_now', label: 'Just now' },
{ key: 'last_1h', label: 'Last hour' },
{ key: 'last_day', label: 'Last day' },
]
function getQuickRange(preset: string): { started_at: string | null; ended_at: string | null } {
const now = new Date()
const iso = (d: Date) => d.toISOString()
if (preset === 'ongoing') return { started_at: iso(now), ended_at: null }
const offsets: Record<string, number> = {
just_now: 15 * 60 * 1000,
last_1h: 60 * 60 * 1000,
last_day: 24 * 60 * 60 * 1000,
}
const ms = offsets[preset]
return ms !== undefined
? { started_at: iso(new Date(now.getTime() - ms)), ended_at: iso(now) }
: { started_at: null, ended_at: null }
}
const form = ref({
label: '', issue_type: '', severity: 'medium', notes: '',
started_at: null as string | null, ended_at: null as string | null,
started_at_local: '', ended_at_local: '',
})
const activePreset = ref<string | null>(null)
const showCustomPicker = ref(false)
const submitting = ref(false)
const submitError = ref('')
function applyPreset(key: string) {
activePreset.value = key
showCustomPicker.value = false
const range = getQuickRange(key)
form.value = { ...form.value, started_at: range.started_at, ended_at: range.ended_at }
}
function toggleCustomPicker() {
showCustomPicker.value = !showCustomPicker.value
if (showCustomPicker.value) activePreset.value = 'custom'
}
const windowSummary = computed(() => {
const start = showCustomPicker.value ? localToIso(form.value.started_at_local) : form.value.started_at
const end = showCustomPicker.value ? localToIso(form.value.ended_at_local) : form.value.ended_at
if (!start && !end) return ''
return `${start ? fmtTs(start) : '—'}${end ? fmtTs(end) : 'ongoing'}`
})
function localToIso(local: string): string | null {
if (!local) return null
return new Date(local).toISOString()
}
async function submit() {
submitError.value = ''
if (!form.value.label.trim()) return
const started_at = showCustomPicker.value ? localToIso(form.value.started_at_local) : form.value.started_at
const ended_at = showCustomPicker.value ? localToIso(form.value.ended_at_local) : form.value.ended_at
submitting.value = true
try {
const res = await fetch(`${BASE}/api/incidents`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
label: form.value.label, issue_type: form.value.issue_type,
severity: form.value.severity, notes: form.value.notes,
started_at, ended_at,
}),
})
if (!res.ok) throw new Error(await res.text())
emit('created', form.value.label)
form.value = { label: '', issue_type: '', severity: 'medium', notes: '', started_at: null, ended_at: null, started_at_local: '', ended_at_local: '' }
activePreset.value = null
showCustomPicker.value = false
} catch (e: unknown) {
submitError.value = e instanceof Error ? e.message : 'Failed to create incident'
} finally {
submitting.value = false
}
}
function fmtTs(iso: string): string {
try {
return new Date(iso).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
} catch { return iso }
}
</script>

View file

@ -0,0 +1,252 @@
<template>
<div>
<!-- Input row -->
<div class="flex gap-3 mb-6">
<input
v-model="query"
type="text"
placeholder='e.g. "plex stopped playing audio around 2pm"'
class="flex-1 bg-surface-raised border border-surface-border rounded px-4 py-2.5 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent transition-colors"
@keydown.enter="run()"
/>
<button
:disabled="loading || !query.trim()"
@click="run()"
class="px-6 py-2.5 rounded bg-accent text-white text-sm font-semibold hover:bg-blue-400 transition-colors disabled:opacity-50"
>
<span v-if="loading">Searching</span>
<span v-else>Go</span>
</button>
</div>
<!-- Error -->
<div v-if="error" class="mb-4 p-3 rounded bg-red-900/30 border border-red-700/40 text-sev-error text-sm">
{{ error }}
</div>
<!-- Summary header -->
<div v-if="summary" class="mb-4 rounded border border-surface-border bg-surface-raised p-4">
<div class="flex flex-wrap gap-x-6 gap-y-1 text-xs text-text-dim">
<span class="text-text-muted font-medium">{{ summary.total }} entr{{ summary.total !== 1 ? 'ies' : 'y' }}</span>
<span v-if="summary.window_start">
{{ fmtTs(summary.window_start) }} {{ fmtTs(summary.window_end) }}
</span>
<span v-if="!summary.time_detected" class="italic">(last 60 min no time detected)</span>
<span
v-for="(count, sev) in nonZeroSeverity"
:key="String(sev)"
:class="sevClass(String(sev))"
>{{ count }} {{ sev }}</span>
</div>
<div class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-text-dim mt-2">
<span v-for="(count, src) in summary.by_source" :key="String(src)">
{{ String(src).split(':').pop() }} ({{ count }})
</span>
</div>
</div>
<!-- Log stream -->
<div v-if="entries.length" class="rounded border border-surface-border overflow-hidden mb-4">
<LogEntryRow v-for="entry in entries" :key="entry.entry_id" :entry="entry" />
</div>
<!-- Zero state -->
<div v-else-if="ranOnce && !loading" class="text-center text-text-dim py-12">
<p class="mb-1">No log evidence found for "{{ lastQuery }}"</p>
<p class="text-sm">Check the Sources tab to confirm data is ingested, or try a broader description.</p>
</div>
<!-- Save CTAs -->
<div v-if="entries.length && !saved" class="mt-2 flex items-center gap-4">
<button
@click="saveQuick"
:disabled="saving"
class="px-4 py-2 bg-accent text-surface text-sm rounded font-medium hover:opacity-90 transition-opacity disabled:opacity-40"
>
{{ saving ? 'Saving…' : 'Save as incident' }}
</button>
<button
v-if="!showDetails"
@click="showDetails = true"
class="text-text-dim hover:text-text-primary text-sm underline underline-offset-2"
>
add details
</button>
</div>
<!-- Inline details panel -->
<div v-if="showDetails && !saved" class="mt-4 rounded border border-surface-border bg-surface-raised p-4 space-y-3">
<div class="flex flex-wrap gap-3">
<div>
<label class="block text-xs text-text-dim mb-1">Severity</label>
<select
v-model="detailSeverity"
class="bg-surface border border-surface-border rounded px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:border-accent"
>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
<option value="critical">Critical</option>
</select>
</div>
<div class="flex-1 min-w-48">
<label class="block text-xs text-text-dim mb-1">Notes <span class="text-text-dim">(optional)</span></label>
<input
v-model="detailNotes"
type="text"
placeholder="Any extra context…"
class="w-full bg-surface border border-surface-border rounded px-3 py-1.5 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent"
/>
</div>
</div>
<div class="flex gap-3">
<button
@click="saveWithDetails"
:disabled="saving"
class="px-4 py-2 bg-accent text-surface text-sm rounded font-medium hover:opacity-90 transition-opacity disabled:opacity-40"
>
{{ saving ? 'Saving…' : 'Save' }}
</button>
<button @click="showDetails = false" class="text-text-dim hover:text-text-primary text-sm">Cancel</button>
</div>
</div>
<!-- Saved confirmation -->
<div v-if="saved" class="mt-2 text-sm text-green-400">
Saved
<RouterLink to="/incidents" class="underline underline-offset-2 hover:text-green-300">view in Incidents</RouterLink>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, RouterLink } from 'vue-router'
import LogEntryRow from '@/components/LogEntryRow.vue'
import type { LogEntry } from '@/stores/search'
const BASE = import.meta.env.BASE_URL.replace(/\/$/, '')
const route = useRoute()
interface Summary {
total: number
window_start: string | null
window_end: string | null
time_detected: boolean
by_severity: Record<string, number>
by_source: Record<string, number>
}
const query = ref('')
const entries = ref<LogEntry[]>([])
const summary = ref<Summary | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const ranOnce = ref(false)
const lastQuery = ref('')
const saved = ref(false)
const saving = ref(false)
const showDetails = ref(false)
const detailSeverity = ref('medium')
const detailNotes = ref('')
let capturedSince: string | null = null
let capturedUntil: string | null = null
onMounted(() => {
const q = route.query.q
if (typeof q === 'string' && q.trim()) {
query.value = q
run()
}
})
watch(() => route.query.q, (newQ) => {
if (typeof newQ === 'string' && newQ.trim() && newQ !== lastQuery.value) {
query.value = newQ
run()
}
})
async function run() {
if (!query.value.trim()) return
loading.value = true
error.value = null
ranOnce.value = true
lastQuery.value = query.value
saved.value = false
showDetails.value = false
try {
const res = await fetch(`${BASE}/api/diagnose`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: query.value }),
})
if (!res.ok) throw new Error(`API returned ${res.status}`)
const data = await res.json()
entries.value = data.entries
summary.value = data.summary
capturedSince = data.summary.window_start
capturedUntil = data.summary.window_end
} catch (e) {
error.value = e instanceof Error ? e.message : String(e)
} finally {
loading.value = false
}
}
async function saveQuick() {
saving.value = true
try { await postIncident('medium', '') }
catch (e) { error.value = e instanceof Error ? e.message : 'Failed to save incident' }
finally { saving.value = false }
}
async function saveWithDetails() {
saving.value = true
try { await postIncident(detailSeverity.value, detailNotes.value) }
catch (e) { error.value = e instanceof Error ? e.message : 'Failed to save incident' }
finally { saving.value = false }
}
async function postIncident(severity: string, notes: string) {
const res = await fetch(`${BASE}/api/incidents`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
label: lastQuery.value,
started_at: capturedSince,
ended_at: capturedUntil,
severity,
notes,
}),
})
if (!res.ok) throw new Error(await res.text())
saved.value = true
showDetails.value = false
}
const nonZeroSeverity = computed(() => {
if (!summary.value) return {}
return Object.fromEntries(
Object.entries(summary.value.by_severity).filter(([, v]) => v > 0)
)
})
function sevClass(sev: string): string {
return ({
CRITICAL: 'text-sev-critical',
ERROR: 'text-sev-error',
WARN: 'text-sev-warn',
INFO: 'text-sev-info',
} as Record<string, string>)[sev] ?? 'text-text-dim'
}
function fmtTs(iso: string | null): string {
if (!iso) return '—'
try {
return new Date(iso).toLocaleString(undefined, {
month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit',
})
} catch { return iso }
}
</script>

View file

@ -0,0 +1,31 @@
<template>
<div class="border-b border-surface-border bg-surface px-6 py-2 flex items-center gap-3">
<span class="text-text-dim text-xs whitespace-nowrap">Quick diagnose</span>
<input
v-model="query"
type="text"
placeholder='Describe what broke (e.g. "plex audio dropped around 2pm")'
class="flex-1 bg-surface-raised border border-surface-border rounded px-3 py-1.5 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent transition-colors"
@keydown.enter="submit"
/>
<button
:disabled="!query.trim()"
@click="submit"
class="px-4 py-1.5 rounded bg-accent text-white text-xs font-semibold hover:bg-blue-400 transition-colors disabled:opacity-50 whitespace-nowrap"
>Go</button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const query = ref('')
function submit() {
if (!query.value.trim()) return
router.push({ path: '/diagnose', query: { q: query.value, tab: 'quick' } })
query.value = ''
}
</script>

View file

@ -0,0 +1,60 @@
<template>
<div>
<button
@click="open = true"
class="fixed bottom-6 right-6 w-12 h-12 rounded-full bg-accent text-white shadow-lg flex items-center justify-center text-xl hover:bg-blue-400 transition-colors z-50"
aria-label="Quick diagnose"
title="Quick diagnose"
></button>
<Teleport to="body">
<div
v-if="open"
class="fixed inset-0 z-40 flex items-end justify-end pb-24 pr-6"
@click.self="open = false"
>
<div class="bg-surface border border-surface-border rounded-xl shadow-xl p-4 w-80 space-y-3">
<p class="text-text-dim text-xs">Describe what broke:</p>
<input
ref="inputRef"
v-model="query"
type="text"
placeholder='e.g. "plex audio dropped around 2pm"'
class="w-full bg-surface-raised border border-surface-border rounded px-3 py-2 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent"
@keydown.enter="submit"
@keydown.esc="open = false"
/>
<div class="flex gap-2 justify-end">
<button @click="open = false" class="px-3 py-1.5 text-xs text-text-dim hover:text-text-primary">Cancel</button>
<button
:disabled="!query.trim()"
@click="submit"
class="px-4 py-1.5 rounded bg-accent text-white text-xs font-semibold hover:bg-blue-400 disabled:opacity-50"
>Go</button>
</div>
</div>
</div>
</Teleport>
</div>
</template>
<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const open = ref(false)
const query = ref('')
const inputRef = ref<HTMLInputElement | null>(null)
watch(open, (val) => {
if (val) nextTick(() => inputRef.value?.focus())
})
function submit() {
if (!query.value.trim()) return
router.push({ path: '/diagnose', query: { q: query.value, tab: 'quick' } })
query.value = ''
open.value = false
}
</script>

View file

@ -5,6 +5,7 @@ import DiagnoseView from '@/views/DiagnoseView.vue'
import SourcesView from '@/views/SourcesView.vue'
import IncidentsView from '@/views/IncidentsView.vue'
import BundlesView from '@/views/BundlesView.vue'
import SettingsView from '@/views/SettingsView.vue'
export default createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
@ -16,5 +17,6 @@ export default createRouter({
{ path: '/incidents', component: IncidentsView },
{ path: '/bundles', component: BundlesView },
{ path: '/sources', component: SourcesView },
{ path: '/settings', component: SettingsView },
],
})

View file

@ -1,108 +1,69 @@
<template>
<div class="p-6 max-w-4xl mx-auto">
<div class="mb-6">
<div class="mb-5">
<h1 class="text-text-primary text-xl font-semibold mb-1">Diagnose</h1>
<p class="text-text-dim text-sm">
Describe a symptom or service name. Turnstone runs layered searches broad relevance,
then CRITICAL/ERROR and returns deduplicated evidence sorted by time.
Quick: describe a symptom to surface log evidence.
Structured: tag a timestamped incident record.
</p>
</div>
<div class="flex gap-3 mb-6">
<input
v-model="symptom"
type="text"
placeholder="e.g. 'plex EAE audio' or 'ssh authentication failed'"
class="flex-1 bg-surface-raised border border-surface-border rounded px-4 py-2.5 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent transition-colors"
@keydown.enter="run()"
/>
<!-- Tab toggle -->
<div class="flex gap-1 mb-6 border-b border-surface-border">
<button
class="px-6 py-2.5 rounded bg-accent text-white text-sm font-semibold hover:bg-blue-400 transition-colors disabled:opacity-50"
:disabled="loading || !symptom.trim()"
@click="run()"
v-for="t in tabs"
:key="t.key"
@click="activeTab = t.key"
:class="[
'px-4 py-2 text-sm transition-colors border-b-2 -mb-px',
activeTab === t.key
? 'border-accent text-accent'
: 'border-transparent text-text-muted hover:text-text-primary'
]"
>{{ t.label }}</button>
</div>
<!-- Quick tab -->
<QuickCapture v-if="activeTab === 'quick'" />
<!-- Structured tab -->
<template v-else>
<IncidentForm @created="onCreated" />
<div
v-if="createdLabel"
class="mt-4 p-3 rounded bg-green-900/30 border border-green-700/40 text-green-400 text-sm"
>
<span v-if="loading">Diagnosing</span>
<span v-else>Diagnose</span>
</button>
</div>
<!-- Error -->
<div v-if="error" class="mb-4 p-3 rounded bg-red-900/30 border border-red-700/40 text-sev-error text-sm">
{{ error }}
</div>
<!-- Results -->
<template v-if="entries.length">
<div class="mb-3 text-text-dim text-xs">
{{ entries.length }} relevant log{{ entries.length !== 1 ? 's' : '' }} sorted chronologically
</div>
<!-- Plain-text summary (pre-formatted for LLM context) -->
<div v-if="formatted" class="mb-4 rounded border border-surface-border bg-surface-raised p-4 overflow-x-auto">
<p class="text-text-dim text-xs uppercase tracking-widest mb-2">Formatted summary</p>
<pre class="text-text-muted text-xs whitespace-pre-wrap leading-relaxed font-mono">{{ formatted }}</pre>
</div>
<div class="rounded border border-surface-border overflow-hidden">
<LogEntryRow
v-for="entry in entries"
:key="entry.entry_id"
:entry="entry"
/>
Incident "{{ createdLabel }}" saved
<RouterLink to="/incidents" class="underline underline-offset-2">view in Incidents</RouterLink>
</div>
</template>
<!-- Zero state after run -->
<div v-else-if="ranOnce && !loading" class="text-center text-text-dim py-12">
<p class="mb-1">No log evidence found for "{{ lastQuery }}"</p>
<p class="text-sm">Check the Sources tab to confirm data is ingested, or try a broader description.</p>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import type { LogEntry } from '@/stores/search'
import LogEntryRow from '@/components/LogEntryRow.vue'
import { ref, onMounted, watch } from 'vue'
import { useRoute, RouterLink } from 'vue-router'
import QuickCapture from '@/components/QuickCapture.vue'
import IncidentForm from '@/components/IncidentForm.vue'
const route = useRoute()
const symptom = ref('')
const entries = ref<LogEntry[]>([])
const formatted = ref('')
const loading = ref(false)
const error = ref<string | null>(null)
const ranOnce = ref(false)
const lastQuery = ref('')
const BASE = import.meta.env.BASE_URL.replace(/\/$/, '')
const tabs: { key: 'quick' | 'structured'; label: string }[] = [
{ key: 'quick', label: 'Quick' },
{ key: 'structured', label: 'Structured' },
]
const activeTab = ref<'quick' | 'structured'>('quick')
const createdLabel = ref('')
onMounted(() => {
const q = route.query.q
if (typeof q === 'string' && q.trim()) {
symptom.value = q
run()
}
if (route.query.tab === 'structured') activeTab.value = 'structured'
})
async function run() {
if (!symptom.value.trim()) return
loading.value = true
error.value = null
lastQuery.value = symptom.value
try {
const url = new URL(`${BASE}/api/diagnose`, window.location.origin)
url.searchParams.set('q', symptom.value)
const res = await fetch(url.toString())
if (!res.ok) throw new Error(`API returned ${res.status}`)
const data = await res.json()
entries.value = data.results
formatted.value = data.formatted ?? ''
ranOnce.value = true
} catch (e) {
error.value = e instanceof Error ? e.message : String(e)
} finally {
loading.value = false
}
watch(() => route.query.tab, (tab) => {
if (tab === 'structured' || tab === 'quick') activeTab.value = tab
})
function onCreated(label: string) {
createdLabel.value = label
setTimeout(() => { createdLabel.value = '' }, 4000)
}
</script>

View file

@ -4,151 +4,20 @@
<!-- Header -->
<div class="mb-6">
<h1 class="text-text-primary text-xl font-semibold mb-1">Incidents</h1>
<p class="text-text-dim text-sm">Tag time windows with descriptions. The label is used to search for related log entries.</p>
</div>
<!-- Create form -->
<div class="mb-8 rounded border border-surface-border bg-surface-raised p-5">
<h2 class="text-text-primary text-sm font-semibold mb-4 uppercase tracking-wider">Tag New Incident</h2>
<div class="space-y-4">
<!-- Label -->
<div>
<label class="block text-xs text-text-dim mb-1">Description <span class="text-accent">*</span></label>
<input
v-model="form.label"
type="text"
placeholder='e.g. "plex stopped playing audio" or "bluetooth kept disconnecting"'
class="w-full bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent"
/>
<p class="text-text-dim text-xs mt-1">Your literal description used to find relevant log entries in the window.</p>
</div>
<!-- Time bucket picker -->
<div>
<label class="block text-xs text-text-dim mb-2">When did it happen?</label>
<div class="flex flex-wrap gap-2 mb-3">
<button
v-for="preset in presets"
:key="preset.key"
@click="applyPreset(preset.key)"
:class="[
'px-3 py-1.5 rounded text-xs border transition-colors',
activePreset === preset.key
? 'bg-accent text-surface border-accent'
: 'bg-surface border-surface-border text-text-muted hover:text-text-primary hover:border-accent'
]"
>
{{ preset.label }}
</button>
<button
@click="toggleCustomPicker"
:class="[
'px-3 py-1.5 rounded text-xs border transition-colors',
showCustomPicker
? 'bg-accent text-surface border-accent'
: 'bg-surface border-surface-border text-text-muted hover:text-text-primary hover:border-accent'
]"
>
Custom range
</button>
</div>
<!-- Custom date range picker -->
<div v-if="showCustomPicker" class="flex flex-wrap gap-3 mt-2">
<div>
<label class="block text-xs text-text-dim mb-1">Start</label>
<input
v-model="form.started_at_local"
type="datetime-local"
class="bg-surface border border-surface-border rounded px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:border-accent"
@change="activePreset = 'custom'"
/>
</div>
<div>
<label class="block text-xs text-text-dim mb-1">End <span class="text-text-dim">(leave blank if ongoing)</span></label>
<input
v-model="form.ended_at_local"
type="datetime-local"
class="bg-surface border border-surface-border rounded px-3 py-1.5 text-sm text-text-primary focus:outline-none focus:border-accent"
@change="activePreset = 'custom'"
/>
</div>
</div>
<!-- Active window summary -->
<p v-if="windowSummary" class="text-text-dim text-xs mt-2">
Window: <span class="text-text-muted">{{ windowSummary }}</span>
<p class="text-text-dim text-sm">
Tagged incidents and their log evidence.
<RouterLink
to="/diagnose?tab=structured"
class="text-accent hover:text-blue-300 underline underline-offset-2 ml-1"
>Tag a new incident </RouterLink>
</p>
</div>
<!-- Issue type -->
<div>
<label class="block text-xs text-text-dim mb-1">Issue type <span class="text-text-dim">(optional short tag for pattern building)</span></label>
<input
v-model="form.issue_type"
type="text"
list="issue-type-suggestions"
placeholder='e.g. "qbit_stall", "auth_failure", "disk_full"'
class="w-full bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent font-mono"
/>
<datalist id="issue-type-suggestions">
<option value="qbit_stall" />
<option value="qbit_crash" />
<option value="auth_failure" />
<option value="disk_full" />
<option value="network_drop" />
<option value="service_crash" />
<option value="permission_error" />
<option value="oom" />
</datalist>
</div>
<!-- Severity + Notes row -->
<div class="flex flex-wrap gap-4">
<div>
<label class="block text-xs text-text-dim mb-1">Severity</label>
<select
v-model="form.severity"
class="bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary focus:outline-none focus:border-accent"
>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
<option value="critical">Critical</option>
</select>
</div>
<div class="flex-1 min-w-48">
<label class="block text-xs text-text-dim mb-1">Notes <span class="text-text-dim">(optional)</span></label>
<input
v-model="form.notes"
type="text"
placeholder="Any extra context…"
class="w-full bg-surface border border-surface-border rounded px-3 py-2 text-sm text-text-primary placeholder-text-dim focus:outline-none focus:border-accent"
/>
</div>
</div>
<!-- Submit -->
<div class="flex items-center gap-3">
<button
@click="submitIncident"
:disabled="!form.label.trim() || submitting"
class="px-4 py-2 bg-accent text-surface text-sm rounded font-medium hover:opacity-90 transition-opacity disabled:opacity-40 disabled:cursor-not-allowed"
>
{{ submitting ? 'Tagging…' : 'Tag Incident' }}
</button>
<span v-if="submitError" class="text-sev-error text-xs">{{ submitError }}</span>
</div>
</div>
</div>
<!-- Incidents table -->
<div v-if="loading" class="text-text-dim py-8 text-center text-sm">Loading</div>
<div v-else-if="incidents.length === 0" class="text-text-dim py-12 text-center text-sm">
No incidents tagged yet. Use the form above to mark your first one.
No incidents tagged yet.
</div>
<div v-else class="rounded border border-surface-border overflow-hidden">
@ -243,7 +112,8 @@
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ref, onMounted } from 'vue'
import { RouterLink } from 'vue-router'
const BASE = import.meta.env.BASE_URL.replace(/\/$/, '')
@ -266,109 +136,6 @@ interface Entry {
text: string
}
const presets = [
{ key: 'ongoing', label: 'Ongoing' },
{ key: 'just_now', label: 'Just now' },
{ key: 'last_1h', label: 'Last hour' },
{ key: 'last_day', label: 'Last day' },
]
function getQuickRange(preset: string): { started_at: string | null; ended_at: string | null } {
const now = new Date()
const iso = (d: Date) => d.toISOString()
if (preset === 'ongoing') {
return { started_at: iso(now), ended_at: null }
}
const offsets: Record<string, number> = {
just_now: 15 * 60 * 1000,
last_1h: 60 * 60 * 1000,
last_day: 24 * 60 * 60 * 1000,
}
const ms = offsets[preset]
return ms !== undefined
? { started_at: iso(new Date(now.getTime() - ms)), ended_at: iso(now) }
: { started_at: null, ended_at: null }
}
// form state
const form = ref({
label: '',
issue_type: '',
severity: 'medium',
notes: '',
started_at: null as string | null,
ended_at: null as string | null,
started_at_local: '',
ended_at_local: '',
})
const activePreset = ref<string | null>(null)
const showCustomPicker = ref(false)
const submitting = ref(false)
const submitError = ref('')
function applyPreset(key: string) {
activePreset.value = key
showCustomPicker.value = false
const range = getQuickRange(key)
form.value.started_at = range.started_at
form.value.ended_at = range.ended_at
}
function toggleCustomPicker() {
showCustomPicker.value = !showCustomPicker.value
if (showCustomPicker.value) activePreset.value = 'custom'
}
const windowSummary = computed(() => {
const start = showCustomPicker.value ? localToIso(form.value.started_at_local) : form.value.started_at
const end = showCustomPicker.value ? localToIso(form.value.ended_at_local) : form.value.ended_at
if (!start && !end) return ''
const s = start ? formatTs(start) : '—'
const e = end ? formatTs(end) : 'ongoing'
return `${s}${e}`
})
function localToIso(local: string): string | null {
if (!local) return null
return new Date(local).toISOString()
}
async function submitIncident() {
submitError.value = ''
if (!form.value.label.trim()) return
const started_at = showCustomPicker.value ? localToIso(form.value.started_at_local) : form.value.started_at
const ended_at = showCustomPicker.value ? localToIso(form.value.ended_at_local) : form.value.ended_at
submitting.value = true
try {
const res = await fetch(`${BASE}/api/incidents`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
label: form.value.label,
issue_type: form.value.issue_type,
severity: form.value.severity,
notes: form.value.notes,
started_at,
ended_at,
}),
})
if (!res.ok) throw new Error(await res.text())
const created: Incident = await res.json()
incidents.value.unshift(created)
form.value = { label: '', issue_type: '', severity: 'medium', notes: '', started_at: null, ended_at: null, started_at_local: '', ended_at_local: '' }
activePreset.value = null
showCustomPicker.value = false
} catch (e: unknown) {
submitError.value = e instanceof Error ? e.message : 'Failed to create incident'
} finally {
submitting.value = false
}
}
// list + delete
const incidents = ref<Incident[]>([])
const loading = ref(true)

View file

@ -0,0 +1,82 @@
<template>
<div class="p-6 max-w-2xl mx-auto">
<div class="mb-6">
<h1 class="text-text-primary text-xl font-semibold mb-1">Settings</h1>
<p class="text-text-dim text-sm">
Turnstone preferences stored alongside the log database.
</p>
</div>
<div class="rounded border border-surface-border bg-surface-raised p-5 space-y-6">
<div>
<h2 class="text-text-primary text-sm font-semibold mb-1">Quick Capture Entry Point</h2>
<p class="text-text-dim text-xs mb-3">
Where the "describe it and search" input appears on every page.
</p>
<div class="flex gap-3">
<button
v-for="opt in entryPointOptions"
:key="opt.value"
@click="setEntryPoint(opt.value as 'topbar' | 'fab')"
:class="[
'flex-1 px-4 py-3 rounded border text-sm transition-colors text-left',
prefs.entry_point_style === opt.value
? 'border-accent bg-accent/10 text-accent'
: 'border-surface-border text-text-muted hover:text-text-primary hover:border-accent'
]"
>
<div class="font-medium">{{ opt.label }}</div>
<div class="text-xs text-text-dim mt-0.5">{{ opt.desc }}</div>
</button>
</div>
<p
v-if="saveStatus"
class="text-xs mt-2"
:class="saveStatus.ok ? 'text-green-400' : 'text-sev-error'"
>
{{ saveStatus.msg }}
</p>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const BASE = import.meta.env.BASE_URL.replace(/\/$/, '')
interface Prefs { entry_point_style: 'topbar' | 'fab' }
const prefs = ref<Prefs>({ entry_point_style: 'topbar' })
const saveStatus = ref<{ ok: boolean; msg: string } | null>(null)
const entryPointOptions = [
{ value: 'topbar', label: 'Top bar', desc: 'Persistent input bar below the nav on every page' },
{ value: 'fab', label: 'FAB', desc: 'Floating action button in the bottom-right corner' },
]
onMounted(async () => {
try {
const res = await fetch(`${BASE}/api/settings`)
if (res.ok) prefs.value = await res.json()
} catch { /* non-critical — default stays topbar */ }
})
async function setEntryPoint(style: 'topbar' | 'fab') {
prefs.value = { entry_point_style: style }
saveStatus.value = null
try {
const res = await fetch(`${BASE}/api/settings`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ entry_point_style: style }),
})
if (!res.ok) throw new Error(await res.text())
saveStatus.value = { ok: true, msg: 'Saved' }
setTimeout(() => { saveStatus.value = null }, 2000)
} catch {
saveStatus.value = { ok: false, msg: 'Save failed — check server connection' }
}
}
</script>