feat: Project Journal backend monorepo

Monorepo with centralized build props, npm workspaces, LlamaSharp AI,
SQLite/SQLCipher storage, Svelte frontend, and unified smoke tests.

Co-Authored-By: Oz <oz-agent@warp.dev>
This commit is contained in:
Jacob Schmidt 2026-02-21 02:01:00 -06:00
commit 0d77300c22
260 changed files with 34066 additions and 0 deletions

5
.editorconfig Normal file
View File

@ -0,0 +1,5 @@
[*.cs]
# Prefer expression body for single-line constructors/methods/properties
csharp_style_expression_bodied_constructors = when_on_single_line:suggestion
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
csharp_style_expression_bodied_properties = true:suggestion

58
.gitignore vendored Normal file
View File

@ -0,0 +1,58 @@
# Build output
bin/
obj/
# Visual Studio
.vs/
*.user
*.suo
*.userosscache
*.sln.docstates
# Rider
.idea/
*.sln.iml
# VS Code
.vscode/
# NuGet
*.nupkg
**/packages/
project.lock.json
project.fragment.lock.json
.nuget/
.dotnet_home/
.journal-sidecar/
.tmp
.npm
output/
# Publish output
publish/
# User secrets
secrets.json
# Windows
Thumbs.db
desktop.ini
# Runtime journal data (created by sidecar at repo root)
journal/
logs/
# macOS
.DS_Store
# Node
node_modules/
# OTHER
.just/
journalapp.exe
journalapp(1).exe
.cache/
Journal.DevTool/scripts/__pycache__/
.sdt/
devtool.backup.json

7
Directory.Build.props Normal file
View File

@ -0,0 +1,7 @@
<Project>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

16
Directory.Packages.props Normal file
View File

@ -0,0 +1,16 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.3" />
<PackageVersion Include="Microsoft.Data.Sqlite.Core" Version="10.0.3" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.3" />
<PackageVersion Include="SQLitePCLRaw.bundle_e_sqlcipher" Version="2.1.11" />
<PackageVersion Include="NAudio" Version="2.2.1" />
<PackageVersion Include="Whisper.net" Version="1.9.0" />
<PackageVersion Include="Whisper.net.Runtime" Version="1.9.0" />
<PackageVersion Include="LLamaSharp" Version="0.26.0" />
<PackageVersion Include="LLamaSharp.Backend.Cpu" Version="0.26.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,35 @@
You are a personal coach inside a private journaling app.
Your goals:
- Be supportive, practical, and brief.
- Ask at most {{maxQuestions}} questions.
- Suggest at most {{maxNextActions}} next actions.
- Default to small, realistic steps.
Hard rules:
- Do not diagnose medical or mental health conditions.
- Do not use shame, guilt, or alarmist language.
- Do not claim certainty about the user's feelings or motives.
- Treat all suggestions as optional proposals.
- Output MUST be a single valid JSON object with NO text before or after it.
- Do NOT output explanations, templates, or examples — only the final JSON.
- If context is missing, make gentle assumptions and ask 1 clarifying question.
Evidence:
- When making an observation or suggestion, include evidence snippets with recordId when available.
You MUST respond with a single valid JSON object. No text before or after the JSON.
Required JSON schema:
{
"kind": "daily_checkin" | "evening_review" | "weekly_review",
"title": "<short title>",
"summary": "<2-4 sentence summary>",
"questions": ["<question>"],
"suggestedNextActions": ["<action>"],
"suggestedTags": ["<tag>"],
"evidence": [{"recordId": null, "text": "<snippet>"}],
"patchProposal": null
}
The top-level "kind" MUST be exactly one of: "daily_checkin", "evening_review", "weekly_review".
Set patchProposal to null unless a draft is clearly helpful. If needed use: {"kind": "createDraft", "description": "<why>", "content": "<markdown>"}.
Do NOT confuse patchProposal.kind with the top-level kind field.

View File

@ -0,0 +1,20 @@
{{CoachRules}}
Task:
Generate a DAILY CHECK-IN plan for date {{dateLocal}}.
Context (JSON):
{{contextJson}}
Preferences (JSON):
{{preferencesJson}}
Output:
Return a CoachPlanDto JSON with kind="daily_checkin".
Include:
- A short title
- A 2-4 sentence summary
- 1-{{maxQuestions}} questions
- 1-{{maxNextActions}} suggestedNextActions
- suggestedTags if relevant
- patchProposal that creates a fragment or dailyEntry draft ONLY if it is clearly helpful.

View File

@ -0,0 +1,19 @@
{{CoachRules}}
Task:
Generate an EVENING REVIEW for date {{dateLocal}}.
Context (JSON):
{{contextJson}}
Preferences (JSON):
{{preferencesJson}}
Output:
Return a CoachPlanDto JSON with kind="evening_review".
Include:
- Brief recap of today
- 2-4 observations with evidence
- 1-{{maxQuestions}} reflection questions
- 1-{{maxNextActions}} next actions for tomorrow
- patchProposal that creates: (optional) tomorrow-intent fragment AND/OR todos.

View File

@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="LLamaSharp" />
<PackageReference Include="LLamaSharp.Backend.Cpu" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Journal.Core\Journal.Core.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Coach-Rules.txt" />
<EmbeddedResource Include="Daily-Check-In.txt" />
<EmbeddedResource Include="Evening-Review.txt" />
<EmbeddedResource Include="Weekly-Review.txt" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,329 @@
using System.Text;
using System.Text.RegularExpressions;
using Journal.Core.Dtos;
using Journal.Core.Models;
using Journal.Core.Services.Ai;
using LLama;
using LLama.Common;
using LLama.Sampling;
namespace Journal.AI;
public sealed partial class LlamaSharpAiService(JournalConfig config) : IAiService, IDisposable
{
private const string DefaultModelUrl =
"https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-gguf/resolve/main/Phi-3-mini-4k-instruct-q4.gguf";
private const string DefaultModelFileName = "Phi-3-mini-4k-instruct-q4.gguf";
private const string ModelSubDirectory = "ai-models";
private readonly string _configuredModelPath = config.GgufModelPath;
private readonly uint _contextSize = (uint)Math.Clamp(config.ModelContextTokens, 512, 4096);
private readonly int _gpuLayers = config.LlamaCppTimeout;
private readonly Lock _sync = new();
private string? _resolvedModelPath;
private LLamaWeights? _weights;
private bool _disposed;
public Task<AiHealthDto> HealthAsync(CancellationToken cancellationToken = default)
{
var resolved = _resolvedModelPath ?? _configuredModelPath;
var modelExists = File.Exists(resolved) || File.Exists(GetDefaultModelPath());
var loaded = _weights is not null;
return Task.FromResult(new AiHealthDto(
Provider: "llamasharp",
Enabled: true,
Healthy: modelExists || loaded,
Message: loaded
? "Model loaded."
: modelExists
? "Model found (will load on first use)."
: "Model not found locally. It will be downloaded on first use."));
}
private static string BuildChatSystemPrompt()
{
var dateStr = DateTime.Now.ToString("MMMM d, yyyy");
return $"You are a supportive conversational coach inside a private journaling app. " +
$"Today's date is {dateStr}. " +
$"Reply in plain natural language only. Never output JSON, code blocks, or structured data. " +
$"Be warm, practical, and concise. Do not repeat yourself.";
}
public async Task<string> ChatAsync(string prompt, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(prompt))
throw new ArgumentException("Prompt is required.", nameof(prompt));
var raw = await RunSessionAsync(prompt, BuildChatSystemPrompt(),
maxTokens: 512, cancellationToken: cancellationToken);
return CleanChatResponse(raw);
}
public async Task<string> ChatWithHistoryAsync(IReadOnlyList<(string Role, string Text)> history,
string prompt, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(prompt))
throw new ArgumentException("Prompt is required.", nameof(prompt));
var modelPath = await EnsureModelAsync(cancellationToken);
EnsureWeights(modelPath);
using var context = _weights!.CreateContext(new ModelParams(modelPath)
{
ContextSize = _contextSize,
GpuLayerCount = _gpuLayers
});
var executor = new StatelessExecutor(_weights!, context.Params);
var sb = new StringBuilder();
sb.Append($"<|system|>\n{BuildChatSystemPrompt()}<|end|>\n");
foreach (var (role, text) in history)
{
var tag = string.Equals(role, "user", StringComparison.OrdinalIgnoreCase) ? "user" : "assistant";
sb.Append($"<|{tag}|>\n{text}<|end|>\n");
}
sb.Append($"<|user|>\n{prompt}<|end|>\n");
sb.Append("<|assistant|>\n");
var inferenceParams = new InferenceParams
{
MaxTokens = 512,
AntiPrompts = ["<|user|>", "<|system|>", "<|end|>", "<|endoftext|>"],
SamplingPipeline = new DefaultSamplingPipeline { Temperature = 0.7f }
};
var result = new StringBuilder();
await foreach (var token in executor.InferAsync(sb.ToString(), inferenceParams, cancellationToken))
{
result.Append(token);
}
return CleanChatResponse(StripSpecialTokens(result.ToString()));
}
internal async Task<string> ChatJsonAsync(string prompt, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(prompt))
throw new ArgumentException("Prompt is required.", nameof(prompt));
var dateStr = DateTime.Now.ToString("MMMM d, yyyy");
return await RunSessionAsync(prompt,
$"You are a coaching assistant inside a private journaling app. " +
$"Today's date is {dateStr}. " +
$"You MUST respond with ONLY a single valid JSON object. " +
$"Do NOT write any text, explanation, or commentary before or after the JSON. " +
$"Output MUST start with {{ and end with }}.",
maxTokens: 2048, temperature: 0.2f, cancellationToken: cancellationToken);
}
public async Task<string> SummarizeEntryAsync(string content, string? fileStem = null,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(content))
throw new ArgumentException("Entry content is required.", nameof(content));
var prompt = fileStem is not null
? $"Summarize this journal entry ({fileStem}) concisely:\n\n{content}"
: $"Summarize this journal entry concisely:\n\n{content}";
return await ChatAsync(prompt, cancellationToken);
}
public async Task<string> SummarizeAllAsync(IReadOnlyList<string> entries,
CancellationToken cancellationToken = default)
{
if (entries is null || entries.Count == 0)
return "No entries to summarize.";
var combined = string.Join("\n\n---\n\n", entries);
var prompt = $"Summarize the following {entries.Count} journal entries into a concise overview:\n\n{combined}";
return await ChatAsync(prompt, cancellationToken);
}
public async Task<IReadOnlyList<double>> EmbedAsync(string content,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(content))
throw new ArgumentException("Content is required.", nameof(content));
var modelPath = await EnsureModelAsync(cancellationToken);
try
{
EnsureWeights(modelPath);
var embedder = new LLamaEmbedder(_weights!, new ModelParams(modelPath)
{
Embeddings = true,
ContextSize = _contextSize,
GpuLayerCount = _gpuLayers
});
var embeddingArrays = await embedder.GetEmbeddings(content, cancellationToken);
var result = new List<double>();
foreach (var arr in embeddingArrays)
{
foreach (var val in arr)
{
result.Add(val);
}
}
return result;
}
catch
{
return [];
}
}
// ── Model download (mirrors LocalWhisperS2TService.EnsureModelAsync) ───
private static string GetDefaultModelPath()
{
var modelDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"ProjectJournal",
ModelSubDirectory);
return Path.Combine(modelDirectory, DefaultModelFileName);
}
private async Task<string> EnsureModelAsync(CancellationToken cancellationToken = default)
{
if (File.Exists(_configuredModelPath))
return _configuredModelPath;
var defaultPath = GetDefaultModelPath();
if (File.Exists(defaultPath))
return defaultPath;
var modelDirectory = Path.GetDirectoryName(defaultPath)!;
Directory.CreateDirectory(modelDirectory);
var tempPath = defaultPath + ".download";
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromMinutes(30));
using var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMinutes(30);
using var response = await httpClient.GetAsync(DefaultModelUrl,
HttpCompletionOption.ResponseHeadersRead, cts.Token);
response.EnsureSuccessStatusCode();
await using var contentStream = await response.Content.ReadAsStreamAsync(cts.Token);
await using var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None);
await contentStream.CopyToAsync(fileStream, cts.Token);
await fileStream.FlushAsync(cts.Token);
fileStream.Close();
File.Move(tempPath, defaultPath, overwrite: true);
return defaultPath;
}
// ── Session / weights lifecycle ────────────────────────────────────────
private Task<string> RunSessionAsync(string prompt, string systemPrompt,
int maxTokens, CancellationToken cancellationToken)
=> RunSessionAsync(prompt, systemPrompt, maxTokens, temperature: 0.7f, cancellationToken);
private async Task<string> RunSessionAsync(string prompt, string systemPrompt,
int maxTokens, float temperature, CancellationToken cancellationToken)
{
var modelPath = await EnsureModelAsync(cancellationToken);
EnsureWeights(modelPath);
using var context = _weights!.CreateContext(new ModelParams(modelPath)
{
ContextSize = _contextSize,
GpuLayerCount = _gpuLayers
});
var executor = new StatelessExecutor(_weights!, context.Params);
var fullPrompt = $"<|system|>\n{systemPrompt}<|end|>\n" +
$"<|user|>\n{prompt}<|end|>\n" +
$"<|assistant|>\n";
var inferenceParams = new InferenceParams
{
MaxTokens = maxTokens,
AntiPrompts = [
"<|user|>",
"<|system|>",
"<|end|>",
"<|endoftext|>",
],
SamplingPipeline = new DefaultSamplingPipeline
{
Temperature = temperature
}
};
var sb = new StringBuilder();
await foreach (var token in executor.InferAsync(fullPrompt, inferenceParams, cancellationToken))
{
sb.Append(token);
}
return StripSpecialTokens(sb.ToString());
}
private static string StripSpecialTokens(string raw)
{
var text = raw;
foreach (var marker in new[] { "<|assistant|>", "<|user|>", "<|system|>", "<|end|>", "<|endoftext|>" })
text = text.Replace(marker, "");
return text.Trim();
}
private static readonly Regex RoleMarkerRegex = MyRegex();
private static string CleanChatResponse(string raw)
{
var text = StripSpecialTokens(raw);
text = RoleMarkerRegex.Replace(text, "");
text = text.Replace("**", "");
text = MyRegex2().Replace(text, "\n\n");
return text.Trim();
}
private void EnsureWeights(string modelPath)
{
if (_weights is not null) return;
lock (_sync)
{
if (_weights is not null) return;
_resolvedModelPath = modelPath;
_weights = LLamaWeights.LoadFromFile(new ModelParams(modelPath)
{
ContextSize = _contextSize,
GpuLayerCount = _gpuLayers
});
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_weights?.Dispose();
}
[GeneratedRegex(@"\*{0,2}(System|Assistant|User):\*{0,2}", RegexOptions.IgnoreCase | RegexOptions.Compiled, "en-US")]
private static partial Regex MyRegex();
[GeneratedRegex(@"\n{3,}")]
private static partial Regex MyRegex1();
[GeneratedRegex(@"\n{3,}")]
private static partial Regex MyRegex2();
}

View File

@ -0,0 +1,229 @@
using System.Reflection;
using System.Text;
using System.Text.Json;
using Journal.Core.Dtos;
using Journal.Core.Services.Ai;
namespace Journal.AI;
public sealed class LlamaSharpCoachService(LlamaSharpAiService ai) : ICoachService
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LlamaSharpAiService _ai = ai;
private readonly string _coachRules = LoadEmbeddedResource("Coach-Rules.txt");
private readonly string _dailyTemplate = LoadEmbeddedResource("Daily-Check-In.txt");
private readonly string _eveningTemplate = LoadEmbeddedResource("Evening-Review.txt");
private readonly string _weeklyTemplate = LoadEmbeddedResource("Weekly-Review.txt");
public async Task<CoachPlanDto> DailyCheckInAsync(CoachContextDto context,
CancellationToken cancellationToken = default)
{
var prefs = context.Preferences ?? new CoachPreferencesDto();
var prompt = InterpolateTemplate(_dailyTemplate, context, prefs);
return await RunCoachPromptAsync(prompt, "daily_checkin", cancellationToken);
}
public async Task<CoachPlanDto> EveningReviewAsync(CoachContextDto context,
CancellationToken cancellationToken = default)
{
var prefs = context.Preferences ?? new CoachPreferencesDto();
var prompt = InterpolateTemplate(_eveningTemplate, context, prefs);
return await RunCoachPromptAsync(prompt, "evening_review", cancellationToken);
}
public async Task<CoachPlanDto> WeeklyReviewAsync(CoachContextDto context,
CancellationToken cancellationToken = default)
{
var prefs = context.Preferences ?? new CoachPreferencesDto();
var prompt = InterpolateTemplate(_weeklyTemplate, context, prefs);
return await RunCoachPromptAsync(prompt, "weekly_review", cancellationToken);
}
private async Task<CoachPlanDto> RunCoachPromptAsync(string prompt, string fallbackKind,
CancellationToken cancellationToken)
{
var raw = await _ai.ChatJsonAsync(prompt, cancellationToken);
var json = ExtractJson(raw);
if (json is not null)
{
try
{
var parsed = JsonSerializer.Deserialize<CoachPlanDto>(json, JsonOptions);
if (parsed is not null)
return parsed with { Kind = fallbackKind };
}
catch (JsonException)
{
}
}
return new CoachPlanDto(
Kind: fallbackKind,
Title: "Coach Response",
Summary: raw,
Questions: [],
SuggestedNextActions: [],
SuggestedTags: [],
Evidence: []);
}
private string InterpolateTemplate(string template, CoachContextDto context, CoachPreferencesDto prefs)
{
var contextJson = JsonSerializer.Serialize(new
{
recentEntries = context.RecentEntries ?? [],
recentFragments = context.RecentFragments ?? []
});
var preferencesJson = JsonSerializer.Serialize(new
{
prefs.MaxQuestions,
prefs.MaxNextActions
});
var result = template
.Replace("{{CoachRules}}", _coachRules)
.Replace("{{dateLocal}}", context.DateLocal)
.Replace("{{weekStartLocal}}", context.WeekStartLocal ?? "")
.Replace("{{weekEndLocal}}", context.WeekEndLocal ?? "")
.Replace("{{contextJson}}", contextJson)
.Replace("{{preferencesJson}}", preferencesJson)
.Replace("{{maxQuestions}}", prefs.MaxQuestions.ToString())
.Replace("{{maxNextActions}}", prefs.MaxNextActions.ToString());
return result;
}
private static string? ExtractJson(string text)
{
var codeBlockStart = text.IndexOf("```json", StringComparison.Ordinal);
if (codeBlockStart >= 0)
{
var jsonStart = text.IndexOf('{', codeBlockStart);
var codeBlockEnd = text.IndexOf("```", codeBlockStart + 7, StringComparison.Ordinal);
if (jsonStart >= 0 && codeBlockEnd > jsonStart)
{
var candidate = text[jsonStart..codeBlockEnd].Trim();
if (TryValidateJson(candidate))
return candidate;
}
}
var kindMarker = text.IndexOf("{\"kind\"", StringComparison.Ordinal);
if (kindMarker < 0)
kindMarker = text.IndexOf("{ \"kind\"", StringComparison.Ordinal);
if (kindMarker >= 0)
{
var lastBrace = text.LastIndexOf('}');
if (lastBrace > kindMarker)
{
var candidate = text[kindMarker..(lastBrace + 1)];
if (TryValidateJson(candidate))
return candidate;
}
}
var searchFrom = 0;
var globalLastBrace = text.LastIndexOf('}');
while (searchFrom < text.Length && globalLastBrace > searchFrom)
{
var bracePos = text.IndexOf('{', searchFrom);
if (bracePos < 0 || bracePos >= globalLastBrace)
break;
var candidate = text[bracePos..(globalLastBrace + 1)];
if (TryValidateJson(candidate))
return candidate;
searchFrom = bracePos + 1;
}
var firstBrace = text.IndexOf('{');
if (firstBrace >= 0)
{
var repaired = TryRepairJson(text[firstBrace..]);
if (repaired is not null)
return repaired;
}
return null;
}
private static string? TryRepairJson(string text)
{
var trimmed = text.TrimEnd();
var lastUseful = trimmed.Length - 1;
while (lastUseful >= 0)
{
var ch = trimmed[lastUseful];
if (ch is '}' or ']' or '"' or ',' or ':' or '{' or '[' || char.IsDigit(ch)
|| ch is 't' or 'r' or 'u' or 'e' or 'f' or 'a' or 'l' or 's' or 'n')
break;
lastUseful--;
}
if (lastUseful < 0) return null;
trimmed = trimmed[..(lastUseful + 1)];
if (trimmed.EndsWith(','))
trimmed = trimmed[..^1];
var openBraces = 0;
var openBrackets = 0;
var inString = false;
var escape = false;
foreach (var ch in trimmed)
{
if (escape) { escape = false; continue; }
if (ch == '\\' && inString) { escape = true; continue; }
if (ch == '"') { inString = !inString; continue; }
if (inString) continue;
switch (ch)
{
case '{': openBraces++; break;
case '}': openBraces--; break;
case '[': openBrackets++; break;
case ']': openBrackets--; break;
}
}
if (openBraces <= 0 && openBrackets <= 0) return null;
var sb = new StringBuilder(trimmed);
for (var i = 0; i < openBrackets; i++) sb.Append(']');
for (var i = 0; i < openBraces; i++) sb.Append('}');
var repaired = sb.ToString();
return TryValidateJson(repaired) ? repaired : null;
}
private static bool TryValidateJson(string json)
{
try
{
using var doc = JsonDocument.Parse(json);
return doc.RootElement.ValueKind == JsonValueKind.Object;
}
catch
{
return false;
}
}
private static string LoadEmbeddedResource(string fileName)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = assembly.GetManifestResourceNames()
.FirstOrDefault(n => n.EndsWith(fileName, StringComparison.OrdinalIgnoreCase)) ?? throw new FileNotFoundException($"Embedded resource not found: {fileName}");
using var stream = assembly.GetManifestResourceStream(resourceName)!;
using var reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd().Trim();
}
}

View File

@ -0,0 +1,57 @@
using Journal.Core.Services.Ai;
using Journal.Core.Services.Config;
using Microsoft.Extensions.DependencyInjection;
namespace Journal.AI;
public static class ServiceCollectionExtensions
{
/// <summary>
/// Registers LLamaSharp-based AI and Coach services.
/// Call this AFTER <c>AddFragmentServices()</c> so that <c>IJournalConfigService</c> is available.
/// When the provider is "llamasharp", this replaces the default <c>IAiService</c> registration.
/// </summary>
public static IServiceCollection AddLlamaSharpServices(this IServiceCollection services)
{
// Override IAiService — last registration wins in MS DI
services.AddSingleton<IAiService>(provider =>
{
var config = provider.GetRequiredService<IJournalConfigService>().Current;
if (string.Equals(config.AiProvider, "llamasharp", StringComparison.OrdinalIgnoreCase))
{
try
{
return new LlamaSharpAiService(config);
}
catch (Exception ex)
{
return new DisabledAiService(
provider: "llamasharp",
message: $"LLamaSharp unavailable: {ex.Message}",
healthy: false);
}
}
return new DisabledAiService(config.AiProvider);
});
// Register coach service
services.AddSingleton<ICoachService>(provider =>
{
var config = provider.GetRequiredService<IJournalConfigService>().Current;
var ai = provider.GetRequiredService<IAiService>();
if (ai is LlamaSharpAiService llamaAi)
return new LlamaSharpCoachService(llamaAi);
if (string.Equals(config.AiProvider, "none", StringComparison.OrdinalIgnoreCase))
return new DisabledCoachService();
return new DisabledCoachService(
$"Coach requires llamasharp provider (current: {config.AiProvider}).");
});
return services;
}
}

View File

@ -0,0 +1,19 @@
{{CoachRules}}
Task:
Generate a WEEKLY REVIEW for {{weekStartLocal}} to {{weekEndLocal}}.
Context (JSON):
{{contextJson}}
Preferences (JSON):
{{preferencesJson}}
Output:
Return a CoachPlanDto JSON with kind="weekly_review".
Include:
- Themes (top 2-4) and blockers (top 1-3)
- Wins (top 1-3)
- 1-{{maxQuestions}} questions to set next weeks focus
- 2-{{maxNextActions}} suggestedNextActions
- patchProposal should only propose creating todos or a planning fragment, not editing old entries.

10
Journal.App/.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

View File

@ -0,0 +1,8 @@
node_modules/
build/
.svelte-kit/
.vscode/
dist/
coverage/
target/
src-tauri/target/

77
Journal.App/README.md Normal file
View File

@ -0,0 +1,77 @@
# Journal.App
SvelteKit 5 + Tauri 2 desktop application for Project Journal.
## Tech Stack
- **Frontend**: SvelteKit 5, TypeScript, Vite 6
- **Tauri shell**: Rust (Tauri 2), `tokio` async runtime
- **Backend bridge**: `Journal.Sidecar.exe` managed as a persistent long-lived child process
## Dev Setup
```powershell
npm install
npm run dev # SvelteKit dev server at http://localhost:1420
npm run tauri dev # Tauri desktop window (connects to dev server)
```
## Build Targets
| Command | Output | Use case |
| ------------------------------------------------------------ | ----------------------------------------- | ----------------------------------- |
| `npm run build` | `Journal.App/build/` | Web bundle for `Journal.WebGateway` |
| `.\scripts\publish-app.ps1 -Target web` | `Journal.App/build/` | Same, via script |
| `.\scripts\publish-app.ps1 -Target tauri -TauriBundles none` | `src-tauri/target/release/journalapp.exe` | Raw desktop exe |
| `.\scripts\publish-app.ps1 -Target tauri -TauriBundles nsis` | NSIS installer | Packaged installer |
## Frontend State Management
Svelte stores are the source of truth for all feature state.
### Current Stores
| Store file | State exports | Notes |
| ----------------------------- | --------------------------------------- | ------------------------------------------------- |
| `src/lib/stores/entries.ts` | `entriesStore` | Entry list, `getDefaultEntry`, `createEntryDraft` |
| `src/lib/stores/fragments.ts` | `fragmentsStore` | Fragment CRUD + parse/serialize helpers |
| `src/lib/stores/todos.ts` | `todoListsStore`, `todosStore` | Todo list and item CRUD |
| `src/lib/stores/lists.ts` | `listsStore` | Generic list CRUD, `createListDraft` |
| `src/lib/stores/settings.ts` | `settingsTags`, `settingsFragmentTypes` | Tag/type config |
### Store-First Rule
- Components call **store helper functions** for CRUD operations — not inline mutations.
- Components should focus on rendering, local form state, and invoking store operations.
- Backend calls (`sendCommand`) belong inside store/service helpers, not components.
## Tauri Commands (Rust → Frontend)
| Command | Description |
| ------------------ | ------------------------------------------------------------------------------------ |
| `sidecar_command` | Forward a `CommandEnvelope` to `Journal.Sidecar` stdin/stdout and return parsed JSON |
| `get_sidecar_root` | Get currently resolved sidecar root path |
| `set_sidecar_root` | Override root path (saved to `settings.json`, restarts sidecar) |
| `get_ui_settings` | Load tag/fragment-type settings |
| `set_ui_settings` | Persist tag/fragment-type settings |
| `shutdown` | Stop sidecar, exit app |
## Sidecar Path Resolution
The Rust shell looks for `Journal.Sidecar.exe` starting from the auto-detected repository root:
1. `<root>/Journal.Sidecar.exe`
2. `<root>/publish/Journal.Sidecar.exe`
3. `<root>/Journal.Sidecar/bin/Debug/net10.0/Journal.Sidecar.exe`
4. `<root>/Journal.Sidecar/bin/Release/net10.0/win-x64/publish/Journal.Sidecar.exe`
5. Recursive scan of `<root>/Journal.Sidecar/`
Build the sidecar before running the Tauri app:
```powershell
.\scripts\publish-sidecar.ps1 -Configuration Release -Runtime win-x64
```
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)

36
Journal.App/package.json Normal file
View File

@ -0,0 +1,36 @@
{
"name": "journalapp",
"version": "0.1.0",
"description": "",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"tauri:prebuild": "node ./scripts/tauri-prebuild.mjs",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"tauri": "tauri",
"format": "prettier --write .",
"format:check": "prettier --check ."
},
"license": "MIT",
"dependencies": {
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-dialog": "^2.6.0",
"@tauri-apps/plugin-opener": "^2",
"tauri-plugin-mic-recorder-api": "^2.0.0"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.6",
"@sveltejs/kit": "^2.9.0",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"@tauri-apps/cli": "^2",
"prettier": "^3.8.1",
"prettier-plugin-svelte": "^3.5.0",
"svelte": "^5.0.0",
"svelte-check": "^4.0.0",
"typescript": "~5.6.2",
"vite": "^6.0.3"
}
}

View File

@ -0,0 +1,11 @@
module.exports = {
plugins: ["prettier-plugin-svelte"],
overrides: [
{
files: "*.svelte",
options: {
parser: "svelte",
},
},
],
};

View File

@ -0,0 +1,97 @@
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const appRoot = path.resolve(__dirname, "..");
const repoRoot = path.resolve(appRoot, "..");
const sidecarProject = path.join(
repoRoot,
"Journal.Sidecar",
"Journal.Sidecar.csproj",
);
const publishOutputDir = path.join(repoRoot, "output");
const tauriBinDir = path.join(appRoot, "src-tauri", "bin");
function runtimeForCurrentPlatform() {
const arch = process.arch;
if (process.platform === "win32") {
if (arch === "arm64") return "win-arm64";
return "win-x64";
}
if (process.platform === "linux") {
if (arch === "arm64") return "linux-arm64";
return "linux-x64";
}
if (process.platform === "darwin") {
if (arch === "arm64") return "osx-arm64";
return "osx-x64";
}
throw new Error(
`Unsupported platform '${process.platform}' for sidecar publish.`,
);
}
function sidecarFileName() {
return process.platform === "win32"
? "Journal.Sidecar.exe"
: "Journal.Sidecar";
}
function publishProject(projectPath, runtime) {
const publishArgs = [
"publish",
projectPath,
"-c",
"Release",
"-r",
runtime,
"--self-contained",
"-p:PublishSingleFile=true",
"-p:IncludeNativeLibrariesForSelfExtract=true",
"-p:IncludeAllContentForSelfExtract=true",
"-p:RestoreIgnoreFailedSources=true",
"-p:NuGetAudit=false",
"-o",
publishOutputDir,
];
const publish = spawnSync("dotnet", publishArgs, {
cwd: repoRoot,
stdio: "inherit",
});
if (publish.error) {
throw publish.error;
}
if (publish.status !== 0) {
process.exit(publish.status ?? 1);
}
}
function stageBinary(fileName) {
const publishedBinary = path.join(publishOutputDir, fileName);
const bundledBinary = path.join(tauriBinDir, fileName);
if (!existsSync(publishedBinary)) {
throw new Error(`Published binary not found: ${publishedBinary}`);
}
mkdirSync(tauriBinDir, { recursive: true });
copyFileSync(publishedBinary, bundledBinary);
console.log(`Staged binary for Tauri: ${bundledBinary}`);
}
const runtime = runtimeForCurrentPlatform();
const sidecarName = sidecarFileName();
console.log(
`Publishing sidecar for ${process.platform}/${process.arch} (${runtime})...`,
);
console.log("Publishing Journal.Sidecar...");
publishProject(sidecarProject, runtime);
stageBinary(sidecarName);

7
Journal.App/src-tauri/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas

5777
Journal.App/src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,27 @@
[package]
name = "journalapp"
version = "0.1.0"
description = "A Tauri App"
authors = ["Stan", "J. Schmidt"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "journalapp_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-dialog = "2"
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["process", "io-util", "sync", "time"] }
tauri-plugin-mic-recorder = "2.0.0"

View File

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View File

@ -0,0 +1,12 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"dialog:default",
"opener:default",
"mic-recorder:default"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 995 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 935 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#fff</color>
</resources>

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 552 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 815 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 477 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View File

@ -0,0 +1,709 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashSet;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use tauri::{Emitter, Manager};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use tokio::sync::Mutex;
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct CommandEnvelope {
action: String,
#[serde(default)]
correlation_id: Option<String>,
#[serde(default)]
id: Option<String>,
#[serde(default)]
r#type: Option<String>,
#[serde(default)]
tag: Option<String>,
#[serde(default)]
payload: Option<Value>,
}
const DEFAULT_SETTINGS_TAGS: &[&str] = &["Personal", "Work", "Ideas", "Journal"];
const DEFAULT_FRAGMENT_TYPES: &[&str] = &["Quote", "Snippet", "Reference"];
const DEFAULT_STARTUP_VIEW: &str = "entries";
#[derive(Deserialize, Serialize)]
struct AppSettings {
#[serde(default, skip_serializing_if = "Option::is_none")]
sidecar_root: Option<String>,
#[serde(default = "default_settings_tags")]
tags: Vec<String>,
#[serde(default = "default_fragment_types")]
fragment_types: Vec<String>,
#[serde(default = "default_startup_view")]
default_startup_view: String,
}
impl Default for AppSettings {
fn default() -> Self {
Self {
sidecar_root: None,
tags: default_settings_tags(),
fragment_types: default_fragment_types(),
default_startup_view: default_startup_view(),
}
}
}
fn default_settings_tags() -> Vec<String> {
DEFAULT_SETTINGS_TAGS
.iter()
.map(|v| (*v).to_string())
.collect()
}
fn default_fragment_types() -> Vec<String> {
DEFAULT_FRAGMENT_TYPES
.iter()
.map(|v| (*v).to_string())
.collect()
}
fn default_startup_view() -> String {
DEFAULT_STARTUP_VIEW.to_string()
}
fn normalize_items(values: Vec<String>, fallback: &[&str]) -> Vec<String> {
let mut seen = HashSet::new();
let mut normalized = Vec::new();
for item in values {
let trimmed = item.trim();
if trimmed.is_empty() {
continue;
}
let key = trimmed.to_lowercase();
if seen.insert(key) {
normalized.push(trimmed.to_string());
}
}
if normalized.is_empty() {
return fallback.iter().map(|v| (*v).to_string()).collect();
}
normalized
}
fn normalize_startup_view(value: Option<String>) -> String {
let normalized = value
.unwrap_or_else(default_startup_view)
.trim()
.to_lowercase();
match normalized.as_str() {
"entries" | "calendar" | "fragments" | "todos" | "lists" => normalized,
_ => default_startup_view(),
}
}
struct ManagedSidecar {
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
}
struct ManagedSpeechProcess {
poll_task: tokio::task::JoinHandle<()>,
}
impl ManagedSidecar {
fn start(root: &Path, resource_dir: Option<&Path>) -> Result<Self, String> {
let sidecar_path = resolve_sidecar_path(root, resource_dir)?;
let mut cmd = Command::new(sidecar_path);
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.current_dir(root)
.env("JOURNAL_PROJECT_ROOT", root)
.kill_on_drop(true);
#[cfg(windows)]
cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
let mut child = cmd
.spawn()
.map_err(|err| format!("Failed to start sidecar process: {err}"))?;
let stdin = child
.stdin
.take()
.ok_or_else(|| "Unable to open sidecar stdin.".to_string())?;
let stdout = child
.stdout
.take()
.ok_or_else(|| "Unable to open sidecar stdout.".to_string())?;
Ok(Self {
child,
stdin,
stdout: BufReader::new(stdout),
})
}
fn is_running(&mut self) -> bool {
match self.child.try_wait() {
Ok(None) => true,
Ok(Some(_)) => false,
Err(_) => false,
}
}
async fn send_command_line(&mut self, input_line: &str) -> Result<String, String> {
self.stdin
.write_all(format!("{input_line}\n").as_bytes())
.await
.map_err(|err| format!("Failed writing to sidecar stdin: {err}"))?;
self.stdin
.flush()
.await
.map_err(|err| format!("Failed flushing sidecar stdin: {err}"))?;
let mut response_line = String::new();
let read = self
.stdout
.read_line(&mut response_line)
.await
.map_err(|err| format!("Failed reading sidecar stdout: {err}"))?;
if read == 0 {
return Err("Sidecar stdout closed unexpectedly.".to_string());
}
let trimmed = response_line.trim().to_string();
if trimmed.is_empty() {
return Err("Sidecar returned an empty response line.".to_string());
}
Ok(trimmed)
}
}
impl Drop for ManagedSidecar {
fn drop(&mut self) {}
}
impl ManagedSpeechProcess {
fn is_running(&self) -> bool {
!self.poll_task.is_finished()
}
}
struct SidecarState {
process: Mutex<Option<ManagedSidecar>>,
speech_process: Mutex<Option<ManagedSpeechProcess>>,
root_override: Mutex<Option<PathBuf>>,
config_path: PathBuf,
resource_dir: Option<PathBuf>,
}
fn load_settings(path: &Path) -> AppSettings {
fs::read_to_string(path)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default()
}
fn save_settings(path: &Path, settings: &AppSettings) -> Result<(), String> {
let json = serde_json::to_string_pretty(settings)
.map_err(|e| format!("Failed to serialize settings: {e}"))?;
fs::write(path, json).map_err(|e| format!("Failed to save settings: {e}"))
}
fn auto_detect_root() -> Result<PathBuf, String> {
let mut current =
env::current_dir().map_err(|err| format!("Unable to read current dir: {err}"))?;
loop {
if current.join("Journal.Sidecar").exists() {
return Ok(current);
}
if !current.pop() {
return Err("Unable to locate repository root containing Journal.Sidecar.".to_string());
}
}
}
fn effective_root(root_override: &Option<PathBuf>) -> Result<PathBuf, String> {
if let Some(root) = root_override {
return Ok(root.clone());
}
auto_detect_root()
}
fn resolve_sidecar_path(root: &Path, resource_dir: Option<&Path>) -> Result<PathBuf, String> {
#[cfg(windows)]
let exe_name = "Journal.Sidecar.exe";
#[cfg(not(windows))]
let exe_name = "Journal.Sidecar";
if root.is_file() && root.file_name().and_then(|n| n.to_str()) == Some(exe_name) {
return Ok(root.to_path_buf());
}
let root_exe_path = root.join(exe_name);
if root_exe_path.exists() {
return Ok(root_exe_path);
}
let tauri_bin_sidecar_path = root
.join("Journal.App")
.join("src-tauri")
.join("bin")
.join(exe_name);
if tauri_bin_sidecar_path.exists() {
return Ok(tauri_bin_sidecar_path);
}
let sidecar_src_root = root.join("Journal.Sidecar");
if let Some(path) = find_sidecar_executable(&sidecar_src_root, exe_name) {
return Ok(path);
}
if let Some(resource_dir) = resource_dir {
let resource_sidecar_path = resource_dir.join("bin").join(exe_name);
if resource_sidecar_path.exists() {
return Ok(resource_sidecar_path);
}
}
Err(format!(
"{exe_name} not found in root, Journal.Sidecar tree, or resource dir for {}.",
root.display()
))
}
fn parse_command_response(response_line: &str) -> Result<Value, String> {
serde_json::from_str::<Value>(response_line)
.map_err(|err| format!("Invalid sidecar JSON response: {err}"))
}
fn read_field<'a>(data: &'a Value, camel: &str, pascal: &str) -> Option<&'a Value> {
data.get(camel).or_else(|| data.get(pascal))
}
fn find_sidecar_executable(search_root: &Path, exe_name: &str) -> Option<PathBuf> {
if !search_root.is_dir() {
return None;
}
let mut stack = vec![search_root.to_path_buf()];
while let Some(dir) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for entry in entries {
let Ok(entry) = entry else {
continue;
};
let path = entry.path();
if path.is_dir() {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name == "node_modules" || name == ".git" || name == ".vs" {
continue;
}
}
stack.push(path);
continue;
}
let is_sidecar_exe = path
.file_name()
.and_then(|name| name.to_str())
.map(|name| name.eq_ignore_ascii_case(exe_name))
.unwrap_or(false);
if is_sidecar_exe {
return Some(path);
}
}
}
None
}
async fn send_with_managed_sidecar(
state: &SidecarState,
input_line: &str,
) -> Result<String, String> {
let root = {
let root_override = state.root_override.lock().await;
effective_root(&root_override)?
};
let mut guard = state.process.lock().await;
for attempt in 1..=2 {
let should_start = match guard.as_mut() {
Some(existing) => !existing.is_running(),
None => true,
};
if should_start {
*guard = Some(ManagedSidecar::start(&root, state.resource_dir.as_deref())?);
}
let Some(process) = guard.as_mut() else {
return Err("Sidecar process unavailable.".to_string());
};
match process.send_command_line(input_line).await {
Ok(line) => return Ok(line),
Err(err) => {
*guard = None;
if attempt == 2 {
return Err(err);
}
}
}
}
Err("Failed to send command to sidecar.".to_string())
}
async fn send_sidecar_action(
state: &SidecarState,
action: &str,
payload: Option<Value>,
) -> Result<Value, String> {
let envelope = serde_json::json!({
"action": action,
"payload": payload.unwrap_or_else(|| serde_json::json!({}))
});
let input_line = serde_json::to_string(&envelope)
.map_err(|err| format!("Serialize command failed: {err}"))?;
let response_line = send_with_managed_sidecar(state, &input_line).await?;
let response = parse_command_response(&response_line)?;
let ok = response
.get("ok")
.and_then(|node| node.as_bool())
.unwrap_or(false);
if !ok {
let err = response
.get("error")
.and_then(|node| node.as_str())
.unwrap_or("Sidecar command failed.");
return Err(err.to_string());
}
Ok(response
.get("data")
.cloned()
.unwrap_or_else(|| serde_json::json!({})))
}
async fn stop_managed_sidecar(state: &SidecarState) {
let mut guard = state.process.lock().await;
guard.take();
}
async fn stop_speech_process(state: &SidecarState) -> Result<(), String> {
let mut guard = state.speech_process.lock().await;
if let Some(process) = guard.take() {
process.poll_task.abort();
}
Ok(())
}
#[tauri::command]
async fn get_sidecar_root(state: tauri::State<'_, SidecarState>) -> Result<Value, String> {
let root_override = state.root_override.lock().await.clone();
let root = effective_root(&root_override)?;
Ok(serde_json::json!({
"root": root.to_string_lossy(),
"isCustom": root_override.is_some()
}))
}
#[tauri::command]
async fn set_sidecar_root(
state: tauri::State<'_, SidecarState>,
path: String,
) -> Result<Value, String> {
let (new_override, root) = if path.trim().is_empty() {
let detected = auto_detect_root()?;
(None, detected)
} else {
let new_root = PathBuf::from(&path);
if !new_root.exists() {
return Err(format!(
"Directory '{}' does not exist.",
new_root.display()
));
}
resolve_sidecar_path(&new_root, state.resource_dir.as_deref())?;
(Some(new_root.clone()), new_root)
};
// Stop the current sidecar so it restarts with new root
{
let mut guard = state.process.lock().await;
guard.take();
}
let is_custom = new_override.is_some();
*state.root_override.lock().await = new_override.clone();
let mut settings = load_settings(&state.config_path);
settings.sidecar_root = new_override.map(|p| p.to_string_lossy().into_owned());
save_settings(&state.config_path, &settings)?;
Ok(serde_json::json!({
"root": root.to_string_lossy(),
"isCustom": is_custom
}))
}
#[tauri::command]
async fn get_ui_settings(state: tauri::State<'_, SidecarState>) -> Result<Value, String> {
let settings = load_settings(&state.config_path);
let tags = normalize_items(settings.tags, DEFAULT_SETTINGS_TAGS);
let fragment_types = normalize_items(settings.fragment_types, DEFAULT_FRAGMENT_TYPES);
let startup_view = normalize_startup_view(Some(settings.default_startup_view));
Ok(serde_json::json!({
"tags": tags,
"fragmentTypes": fragment_types,
"defaultStartupView": startup_view
}))
}
#[tauri::command]
async fn set_ui_settings(
state: tauri::State<'_, SidecarState>,
tags: Vec<String>,
fragment_types: Vec<String>,
default_startup_view: Option<String>,
) -> Result<Value, String> {
let mut settings = load_settings(&state.config_path);
settings.tags = normalize_items(tags, DEFAULT_SETTINGS_TAGS);
settings.fragment_types = normalize_items(fragment_types, DEFAULT_FRAGMENT_TYPES);
settings.default_startup_view = normalize_startup_view(default_startup_view);
save_settings(&state.config_path, &settings)?;
Ok(serde_json::json!({
"tags": settings.tags,
"fragmentTypes": settings.fragment_types,
"defaultStartupView": settings.default_startup_view
}))
}
#[tauri::command]
async fn shutdown(
state: tauri::State<'_, SidecarState>,
app_handle: tauri::AppHandle,
) -> Result<(), String> {
stop_speech_process(state.inner()).await?;
let _ = send_sidecar_action(state.inner(), "speech.live.stop", None).await;
stop_managed_sidecar(state.inner()).await;
app_handle.exit(0);
Ok(())
}
#[tauri::command]
async fn speech_start(
state: tauri::State<'_, SidecarState>,
app_handle: tauri::AppHandle,
) -> Result<Value, String> {
let _ = app_handle.emit(
"speech-status",
serde_json::json!({ "state": "starting", "message": "Starting speech process..." }),
);
{
let guard = state.speech_process.lock().await;
if let Some(existing) = guard.as_ref() {
if existing.is_running() {
return Ok(serde_json::json!({ "running": true }));
}
}
}
let start_data = send_sidecar_action(state.inner(), "speech.live.start", None).await?;
let running = read_field(&start_data, "running", "Running")
.and_then(|node| node.as_bool())
.unwrap_or(false);
let status = read_field(&start_data, "status", "Status")
.and_then(|node| node.as_str())
.unwrap_or("starting");
let warning = read_field(&start_data, "warning", "Warning")
.and_then(|node| node.as_str())
.map(|v| v.to_string());
let _ = app_handle.emit(
"speech-status",
serde_json::json!({ "state": status, "message": warning.clone().unwrap_or_else(|| status.to_string()) }),
);
if !running {
return Err(warning.unwrap_or_else(|| "Failed to start live speech.".to_string()));
}
let app_for_poll = app_handle.clone();
let poll_task = tokio::spawn(async move {
loop {
let state_handle = app_for_poll.state::<SidecarState>();
let poll_data = match send_sidecar_action(
state_handle.inner(),
"speech.live.poll",
Some(serde_json::json!({ "maxItems": 8 })),
)
.await
{
Ok(value) => value,
Err(err) => {
let _ = app_for_poll.emit(
"speech-status",
serde_json::json!({ "state": "error", "message": err }),
);
break;
}
};
if let Some(items) =
read_field(&poll_data, "items", "Items").and_then(|node| node.as_array())
{
for item in items {
if let Some(text) = item.as_str() {
let _ = app_for_poll
.emit("speech-transcript", serde_json::json!({ "text": text }));
}
}
}
let running = read_field(&poll_data, "running", "Running")
.and_then(|node| node.as_bool())
.unwrap_or(false);
let status = read_field(&poll_data, "status", "Status")
.and_then(|node| node.as_str())
.unwrap_or(if running { "listening" } else { "stopped" });
let warning = read_field(&poll_data, "warning", "Warning")
.and_then(|node| node.as_str())
.map(|v| v.to_string());
if let Some(message) = warning {
let _ = app_for_poll.emit(
"speech-status",
serde_json::json!({ "state": if running { "listening" } else { "error" }, "message": message }),
);
} else {
let _ = app_for_poll.emit(
"speech-status",
serde_json::json!({ "state": status, "message": status }),
);
}
if !running {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(350)).await;
}
});
let mut guard = state.speech_process.lock().await;
*guard = Some(ManagedSpeechProcess { poll_task });
Ok(serde_json::json!({ "running": true }))
}
#[tauri::command]
async fn speech_stop(
state: tauri::State<'_, SidecarState>,
app_handle: tauri::AppHandle,
) -> Result<Value, String> {
stop_speech_process(state.inner()).await?;
let _ = send_sidecar_action(state.inner(), "speech.live.stop", None).await;
let _ = app_handle.emit(
"speech-status",
serde_json::json!({ "state": "stopped", "message": "Dictation stopped." }),
);
Ok(serde_json::json!({ "running": false }))
}
#[tauri::command]
async fn speech_cleanup_probe(path: String) -> Result<Value, String> {
if path.trim().is_empty() {
return Ok(serde_json::json!({ "deleted": false }));
}
let target = PathBuf::from(path);
let normalized = target.to_string_lossy().to_lowercase();
if !normalized.contains("tauri-plugin-mic-recorder") || !normalized.ends_with(".wav") {
return Ok(serde_json::json!({ "deleted": false }));
}
if !target.exists() {
return Ok(serde_json::json!({ "deleted": false }));
}
fs::remove_file(&target).map_err(|err| format!("Failed to remove probe recording: {err}"))?;
Ok(serde_json::json!({ "deleted": true }))
}
#[tauri::command]
async fn sidecar_command(
state: tauri::State<'_, SidecarState>,
command: CommandEnvelope,
) -> Result<Value, String> {
if command.action.trim().is_empty() {
return Err("Missing action".to_string());
}
let input_line = serde_json::to_string(&command)
.map_err(|err| format!("Serialize command failed: {err}"))?;
let response_line = send_with_managed_sidecar(state.inner(), &input_line).await?;
parse_command_response(&response_line)
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let app = tauri::Builder::default()
.plugin(tauri_plugin_mic_recorder::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.invoke_handler(tauri::generate_handler![
sidecar_command,
shutdown,
speech_start,
speech_stop,
speech_cleanup_probe,
get_sidecar_root,
set_sidecar_root,
get_ui_settings,
set_ui_settings,
])
.setup(|app| {
let config_dir = app.path().app_config_dir()?;
fs::create_dir_all(&config_dir).ok();
let config_path = config_dir.join("settings.json");
let settings = load_settings(&config_path);
let root_override = settings.sidecar_root.map(PathBuf::from);
app.manage(SidecarState {
process: Mutex::new(None),
speech_process: Mutex::new(None),
root_override: Mutex::new(root_override),
config_path,
resource_dir: app.path().resource_dir().ok(),
});
Ok(())
})
.build(tauri::generate_context!())
.expect("error while building tauri application");
app.run(|app_handle, event| {
if let tauri::RunEvent::ExitRequested { .. } = event {
let state = app_handle.state::<SidecarState>();
if let Ok(mut guard) = state.process.try_lock() {
guard.take();
};
if let Ok(mut guard) = state.speech_process.try_lock() {
if let Some(speech) = guard.take() {
speech.poll_task.abort();
}
};
}
});
}

View File

@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
journalapp_lib::run()
}

View File

@ -0,0 +1,36 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Project Journal",
"version": "0.1.0",
"identifier": "com.idsolutions.journal",
"build": {
"beforeDevCommand": "npm run dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "npm run tauri:prebuild && npm run build",
"frontendDist": "../build"
},
"app": {
"windows": [
{
"title": "Project Journal",
"width": 1366,
"height": 768
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"resources": ["bin"],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

19
Journal.App/src/app.html Normal file
View File

@ -0,0 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/icon.ico" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200"
/>
<link rel="stylesheet" href="style.css" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Journal</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View File

@ -0,0 +1,222 @@
import { sendCommand } from "./client";
import { pickCase } from "./normalize";
//#region Public Types
export type AiHealthDto = {
provider: string;
enabled: boolean;
healthy: boolean;
message: string;
};
export type CoachEvidenceDto = {
recordId: string | null;
text: string;
};
export type CoachPatchProposalDto = {
kind: string;
description: string | null;
content: string | null;
};
export type CoachPlanDto = {
kind: string;
title: string;
summary: string;
questions: string[];
suggestedNextActions: string[];
suggestedTags: string[];
evidence: CoachEvidenceDto[];
patchProposal: CoachPatchProposalDto | null;
};
export type CoachPreferencesDto = {
maxQuestions?: number;
maxNextActions?: number;
};
export type CoachSessionPayload = {
dateLocal?: string;
weekStartLocal?: string;
weekEndLocal?: string;
recentEntries?: string[];
recentFragments?: string[];
preferences?: CoachPreferencesDto;
};
//#endregion
//#region PascalCase Normalizers
type AiHealthDtoRaw = {
provider?: string;
enabled?: boolean;
healthy?: boolean;
message?: string;
Provider?: string;
Enabled?: boolean;
Healthy?: boolean;
Message?: string;
};
type CoachEvidenceDtoRaw = {
recordId?: string | null;
text?: string;
RecordId?: string | null;
Text?: string;
};
type CoachPatchProposalDtoRaw = {
kind?: string;
description?: string | null;
content?: string | null;
Kind?: string;
Description?: string | null;
Content?: string | null;
};
type CoachPlanDtoRaw = {
kind?: string;
title?: string;
summary?: string;
questions?: string[];
suggestedNextActions?: string[];
suggestedTags?: string[];
evidence?: CoachEvidenceDtoRaw[];
patchProposal?: CoachPatchProposalDtoRaw | null;
Kind?: string;
Title?: string;
Summary?: string;
Questions?: string[];
SuggestedNextActions?: string[];
SuggestedTags?: string[];
Evidence?: CoachEvidenceDtoRaw[];
PatchProposal?: CoachPatchProposalDtoRaw | null;
};
//#endregion
//#region Normalizers
function normalizeHealth(raw: AiHealthDtoRaw): AiHealthDto {
return {
provider: pickCase(raw, "provider", "Provider", ""),
enabled: pickCase(raw, "enabled", "Enabled", false),
healthy: pickCase(raw, "healthy", "Healthy", false),
message: pickCase(raw, "message", "Message", ""),
};
}
function normalizeEvidence(raw: CoachEvidenceDtoRaw): CoachEvidenceDto {
return {
recordId: pickCase(raw, "recordId", "RecordId", null as string | null),
text: pickCase(raw, "text", "Text", ""),
};
}
function normalizePatchProposal(
raw: CoachPatchProposalDtoRaw | null | undefined,
): CoachPatchProposalDto | null {
if (!raw) return null;
return {
kind: pickCase(raw, "kind", "Kind", ""),
description: pickCase(
raw,
"description",
"Description",
null as string | null,
),
content: pickCase(raw, "content", "Content", null as string | null),
};
}
function normalizeCoachPlan(raw: CoachPlanDtoRaw): CoachPlanDto {
const evidenceRaw = pickCase(
raw,
"evidence",
"Evidence",
[] as CoachEvidenceDtoRaw[],
);
const patchRaw = pickCase(
raw,
"patchProposal",
"PatchProposal",
null as CoachPatchProposalDtoRaw | null,
);
return {
kind: pickCase(raw, "kind", "Kind", ""),
title: pickCase(raw, "title", "Title", ""),
summary: pickCase(raw, "summary", "Summary", ""),
questions: pickCase(raw, "questions", "Questions", [] as string[]),
suggestedNextActions: pickCase(
raw,
"suggestedNextActions",
"SuggestedNextActions",
[] as string[],
),
suggestedTags: pickCase(
raw,
"suggestedTags",
"SuggestedTags",
[] as string[],
),
evidence: evidenceRaw.map(normalizeEvidence),
patchProposal: normalizePatchProposal(patchRaw),
};
}
//#endregion
//#region API Functions
export async function aiHealth(): Promise<AiHealthDto> {
const data = await sendCommand<AiHealthDtoRaw>({
action: "ai.health",
payload: {},
});
return normalizeHealth(data);
}
export async function aiChat(prompt: string): Promise<string> {
return sendCommand<string>({
action: "ai.chat",
payload: { prompt },
});
}
export async function aiSummarizeEntry(
content: string,
fileStem?: string,
): Promise<string> {
return sendCommand<string>({
action: "ai.summarize_entry",
payload: { content, fileStem },
});
}
export async function coachDaily(
payload: CoachSessionPayload = {},
): Promise<CoachPlanDto> {
const data = await sendCommand<CoachPlanDtoRaw>({
action: "ai.coach.daily",
payload,
});
return normalizeCoachPlan(data);
}
export async function coachEvening(
payload: CoachSessionPayload = {},
): Promise<CoachPlanDto> {
const data = await sendCommand<CoachPlanDtoRaw>({
action: "ai.coach.evening",
payload,
});
return normalizeCoachPlan(data);
}
export async function coachWeekly(
payload: CoachSessionPayload = {},
): Promise<CoachPlanDto> {
const data = await sendCommand<CoachPlanDtoRaw>({
action: "ai.coach.weekly",
payload,
});
return normalizeCoachPlan(data);
}
//#endregion

View File

@ -0,0 +1,84 @@
import { sendCommand } from "./client";
import { pickCase } from "./normalize";
export function hydrateWorkspace(password: string): Promise<unknown> {
return sendCommand<unknown>({
action: "db.hydrate_workspace",
payload: { password },
});
}
type RuntimeConfigRaw = {
vaultDirectory?: string;
VaultDirectory?: string;
};
type RuntimeConfig = {
vaultDirectory: string;
};
type PersistOptions = {
keepalive?: boolean;
};
async function getRuntimeConfig(
options: PersistOptions = {},
): Promise<RuntimeConfig> {
const data = await sendCommand<RuntimeConfigRaw>(
{
action: "config.get",
},
options,
);
return {
vaultDirectory: pickCase(data, "vaultDirectory", "VaultDirectory", ""),
};
}
export async function unlockVaultWorkspace(password: string): Promise<void> {
const config = await getRuntimeConfig();
const loaded = await sendCommand<boolean>({
action: "vault.load_all",
payload: {
password,
vaultDirectory: config.vaultDirectory,
},
});
if (!loaded) {
throw new Error("Incorrect vault password.");
}
await sendCommand<unknown>({
action: "db.hydrate_workspace",
payload: {
password,
},
});
}
export async function persistAndClearVault(
password: string,
options: PersistOptions = {},
): Promise<void> {
const config = await getRuntimeConfig(options);
await sendCommand<boolean>(
{
action: "vault.rebuild_all",
payload: {
password,
vaultDirectory: config.vaultDirectory,
},
},
options,
);
await sendCommand<boolean>(
{
action: "vault.clear_data_directory",
payload: {},
},
options,
);
}

View File

@ -0,0 +1,30 @@
import { invoke } from "$lib/runtime/invoke";
import type { BackendCommand, BackendResponse } from "./types";
function newCorrelationId(): string {
return `ui-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
type SendCommandOptions = {
keepalive?: boolean;
};
export async function sendCommand<T>(
command: BackendCommand,
options: SendCommandOptions = {},
): Promise<T> {
const envelope: BackendCommand = {
...command,
correlationId: command.correlationId ?? newCorrelationId(),
};
const response = await invoke<BackendResponse<T>>("sidecar_command", {
command: envelope,
keepalive: options.keepalive === true,
});
if (!response.ok) {
throw new Error(response.error || "Backend command failed");
}
return response.data;
}

View File

@ -0,0 +1,195 @@
import { sendCommand } from "./client";
import { pickCase } from "./normalize";
//#region Public Types
export type ConversationDto = {
id: string;
title: string;
createdAt: string;
updatedAt: string;
};
export type ConversationMessageDto = {
id: string;
role: string;
text: string;
createdAt: string;
};
export type ConversationDetailDto = {
id: string;
title: string;
messages: ConversationMessageDto[];
createdAt: string;
updatedAt: string;
};
export type ConversationChatResult = {
userMessage: ConversationMessageDto;
assistantMessage: ConversationMessageDto;
};
//#endregion
//#region PascalCase Normalizers
type ConversationDtoRaw = {
id?: string;
title?: string;
createdAt?: string;
updatedAt?: string;
Id?: string;
Title?: string;
CreatedAt?: string;
UpdatedAt?: string;
};
type ConversationMessageDtoRaw = {
id?: string;
role?: string;
text?: string;
createdAt?: string;
Id?: string;
Role?: string;
Text?: string;
CreatedAt?: string;
};
type ConversationDetailDtoRaw = {
id?: string;
title?: string;
messages?: ConversationMessageDtoRaw[];
createdAt?: string;
updatedAt?: string;
Id?: string;
Title?: string;
Messages?: ConversationMessageDtoRaw[];
CreatedAt?: string;
UpdatedAt?: string;
};
type ConversationChatResultRaw = {
userMessage?: ConversationMessageDtoRaw;
assistantMessage?: ConversationMessageDtoRaw;
UserMessage?: ConversationMessageDtoRaw;
AssistantMessage?: ConversationMessageDtoRaw;
};
//#endregion
//#region Normalizers
function normalizeMessage(
raw: ConversationMessageDtoRaw,
): ConversationMessageDto {
return {
id: pickCase(raw, "id", "Id", ""),
role: pickCase(raw, "role", "Role", ""),
text: pickCase(raw, "text", "Text", ""),
createdAt: pickCase(raw, "createdAt", "CreatedAt", ""),
};
}
function normalizeConversation(raw: ConversationDtoRaw): ConversationDto {
return {
id: pickCase(raw, "id", "Id", ""),
title: pickCase(raw, "title", "Title", ""),
createdAt: pickCase(raw, "createdAt", "CreatedAt", ""),
updatedAt: pickCase(raw, "updatedAt", "UpdatedAt", ""),
};
}
function normalizeDetail(raw: ConversationDetailDtoRaw): ConversationDetailDto {
const msgs = pickCase(
raw,
"messages",
"Messages",
[] as ConversationMessageDtoRaw[],
);
return {
id: pickCase(raw, "id", "Id", ""),
title: pickCase(raw, "title", "Title", ""),
messages: msgs.map(normalizeMessage),
createdAt: pickCase(raw, "createdAt", "CreatedAt", ""),
updatedAt: pickCase(raw, "updatedAt", "UpdatedAt", ""),
};
}
function normalizeChatResult(
raw: ConversationChatResultRaw,
): ConversationChatResult {
const userRaw = pickCase(
raw,
"userMessage",
"UserMessage",
{} as ConversationMessageDtoRaw,
);
const assistantRaw = pickCase(
raw,
"assistantMessage",
"AssistantMessage",
{} as ConversationMessageDtoRaw,
);
return {
userMessage: normalizeMessage(userRaw),
assistantMessage: normalizeMessage(assistantRaw),
};
}
//#endregion
//#region API Functions
export async function listConversations(): Promise<ConversationDto[]> {
const data = await sendCommand<ConversationDtoRaw[]>({
action: "conversations.list",
payload: {},
});
return (data ?? []).map(normalizeConversation);
}
export async function getConversation(
id: string,
): Promise<ConversationDetailDto> {
const data = await sendCommand<ConversationDetailDtoRaw>({
action: "conversations.get",
id,
payload: {},
});
return normalizeDetail(data);
}
export async function createConversation(
title: string,
): Promise<ConversationDto> {
const data = await sendCommand<ConversationDtoRaw>({
action: "conversations.create",
payload: { title },
});
return normalizeConversation(data);
}
export async function updateConversation(
id: string,
title: string,
): Promise<boolean> {
return sendCommand<boolean>({
action: "conversations.update",
id,
payload: { title },
});
}
export async function deleteConversation(id: string): Promise<boolean> {
return sendCommand<boolean>({
action: "conversations.delete",
id,
payload: {},
});
}
export async function conversationChat(
conversationId: string,
prompt: string,
): Promise<ConversationChatResult> {
const data = await sendCommand<ConversationChatResultRaw>({
action: "conversations.chat",
payload: { conversationId, prompt },
});
return normalizeChatResult(data);
}
//#endregion

View File

@ -0,0 +1,270 @@
import { sendCommand } from "./client";
import {
normalizeFragment,
type FragmentDto,
type FragmentDtoRaw,
} from "./fragments";
import { pickCase } from "./normalize";
export type ParsedSectionDto = {
title: string;
content: string[];
checkboxes: Record<string, boolean>;
};
export type JournalEntryDto = {
date: string;
fragments: FragmentDto[];
rawContent: string;
sections: Record<string, ParsedSectionDto>;
};
export type EntryListItemDto = {
fileName: string;
filePath: string;
};
export type EntryLoadResultDto = {
fileName: string;
filePath: string;
entry: JournalEntryDto;
};
export type EntrySaveResultDto = {
filePath: string;
};
export type EntrySearchRequestDto = {
query?: string;
section?: string;
startDate?: string;
endDate?: string;
tags?: string[];
types?: string[];
checked?: string[];
unchecked?: string[];
};
export type EntrySearchResultDto = {
fileName: string;
entry: JournalEntryDto;
};
type ParsedSectionDtoRaw = {
title?: string;
content?: string[];
checkboxes?: Record<string, boolean>;
Title?: string;
Content?: string[];
Checkboxes?: Record<string, boolean>;
};
type JournalEntryDtoRaw = {
date?: string;
fragments?: FragmentDtoRaw[];
rawContent?: string;
sections?: Record<string, ParsedSectionDtoRaw>;
Date?: string;
Fragments?: FragmentDtoRaw[];
RawContent?: string;
Sections?: Record<string, ParsedSectionDtoRaw>;
};
type EntryListItemDtoRaw = {
fileName?: string;
filePath?: string;
FileName?: string;
FilePath?: string;
};
type EntryLoadResultDtoRaw = {
fileName?: string;
filePath?: string;
entry?: JournalEntryDtoRaw;
date?: string;
rawContent?: string;
FileName?: string;
FilePath?: string;
Entry?: JournalEntryDtoRaw;
Date?: string;
RawContent?: string;
};
type EntrySaveResultDtoRaw = {
filePath?: string;
FilePath?: string;
};
type EntrySearchResultDtoRaw = {
fileName?: string;
entry?: JournalEntryDtoRaw;
date?: string;
rawContent?: string;
FileName?: string;
Entry?: JournalEntryDtoRaw;
Date?: string;
RawContent?: string;
};
function normalizeSection(raw: ParsedSectionDtoRaw): ParsedSectionDto {
return {
title: pickCase(raw, "title", "Title", ""),
content: pickCase(raw, "content", "Content", [] as string[]),
checkboxes: pickCase(
raw,
"checkboxes",
"Checkboxes",
{} as Record<string, boolean>,
),
};
}
function normalizeJournalEntry(
raw: JournalEntryDtoRaw | undefined,
): JournalEntryDto {
const fragments = pickCase(
raw,
"fragments",
"Fragments",
[] as FragmentDtoRaw[],
);
const sections = pickCase(
raw,
"sections",
"Sections",
{} as Record<string, ParsedSectionDtoRaw>,
);
return {
date: pickCase(raw, "date", "Date", ""),
fragments: fragments.map(normalizeFragment),
rawContent: pickCase(raw, "rawContent", "RawContent", ""),
sections: Object.fromEntries(
Object.entries(sections).map(([key, value]) => [
key,
normalizeSection(value),
]),
),
};
}
function normalizeEntryListItem(raw: EntryListItemDtoRaw): EntryListItemDto {
return {
fileName: pickCase(raw, "fileName", "FileName", ""),
filePath: pickCase(raw, "filePath", "FilePath", ""),
};
}
function normalizeEntryLoadResult(
raw: EntryLoadResultDtoRaw,
): EntryLoadResultDto {
const nestedEntry = pickCase(
raw,
"entry",
"Entry",
undefined as JournalEntryDtoRaw | undefined,
);
const entry = nestedEntry
? normalizeJournalEntry(nestedEntry)
: normalizeJournalEntry({
date: pickCase(raw, "date", "Date", undefined as string | undefined),
rawContent: pickCase(
raw,
"rawContent",
"RawContent",
undefined as string | undefined,
),
fragments: [],
sections: {},
});
return {
fileName: pickCase(raw, "fileName", "FileName", ""),
filePath: pickCase(raw, "filePath", "FilePath", ""),
entry,
};
}
function normalizeEntrySearchResult(
raw: EntrySearchResultDtoRaw,
): EntrySearchResultDto {
const nestedEntry = pickCase(
raw,
"entry",
"Entry",
undefined as JournalEntryDtoRaw | undefined,
);
const entry = nestedEntry
? normalizeJournalEntry(nestedEntry)
: normalizeJournalEntry({
date: pickCase(raw, "date", "Date", undefined as string | undefined),
rawContent: pickCase(
raw,
"rawContent",
"RawContent",
undefined as string | undefined,
),
fragments: [],
sections: {},
});
return {
fileName: pickCase(raw, "fileName", "FileName", ""),
entry,
};
}
export async function listEntries(): Promise<EntryListItemDto[]> {
const data = await sendCommand<EntryListItemDtoRaw[]>({
action: "entries.list",
payload: {},
});
return data
.map(normalizeEntryListItem)
.filter((item) => Boolean(item.filePath));
}
export async function loadEntry(filePath: string): Promise<EntryLoadResultDto> {
const data = await sendCommand<EntryLoadResultDtoRaw>({
action: "entries.load",
payload: { filePath },
});
return normalizeEntryLoadResult(data);
}
export async function saveEntry(payload: {
content: string;
filePath?: string;
mode?: string;
fileName?: string;
}): Promise<EntrySaveResultDto> {
const data = await sendCommand<EntrySaveResultDtoRaw>({
action: "entries.save",
payload,
});
return {
filePath: pickCase(data, "filePath", "FilePath", ""),
};
}
export async function deleteEntry(filePath: string): Promise<boolean> {
return sendCommand<boolean>({
action: "entries.delete",
payload: { filePath },
});
}
export async function searchEntries(
payload: EntrySearchRequestDto,
): Promise<EntrySearchResultDto[]> {
const data = await sendCommand<EntrySearchResultDtoRaw[]>({
action: "search.entries",
payload,
});
return data
.map(normalizeEntrySearchResult)
.filter((item) => Boolean(item.fileName));
}

View File

@ -0,0 +1,91 @@
import { sendCommand } from "./client";
import { pickCase } from "./normalize";
export type FragmentDto = {
id: string;
type: string;
description: string;
time: string;
tags: string[];
};
export type CreateFragmentPayload = {
type: string;
description: string;
tags?: string[];
};
export type UpdateFragmentPayload = {
type?: string;
description?: string;
tags?: string[];
time?: string;
};
export type FragmentDtoRaw = {
id?: string;
type?: string;
description?: string;
time?: string;
tags?: string[];
Id?: string;
Type?: string;
Description?: string;
Time?: string;
Tags?: string[];
};
export function normalizeFragment(raw: FragmentDtoRaw): FragmentDto {
return {
id: pickCase(raw, "id", "Id", ""),
type: pickCase(raw, "type", "Type", ""),
description: pickCase(raw, "description", "Description", ""),
time: pickCase(raw, "time", "Time", ""),
tags: pickCase(raw, "tags", "Tags", [] as string[]),
};
}
export async function listFragments(): Promise<FragmentDto[]> {
const data = await sendCommand<FragmentDtoRaw[]>({
action: "fragments.list",
});
return data.map(normalizeFragment).filter((item) => Boolean(item.id));
}
export async function getFragment(id: string): Promise<FragmentDto | null> {
const data = await sendCommand<FragmentDtoRaw | null>({
action: "fragments.get",
id,
});
if (!data) return null;
const normalized = normalizeFragment(data);
return normalized.id ? normalized : null;
}
export async function createFragment(
payload: CreateFragmentPayload,
): Promise<FragmentDto> {
const data = await sendCommand<FragmentDtoRaw>({
action: "fragments.create",
payload,
});
return normalizeFragment(data);
}
export function updateFragment(
id: string,
payload: UpdateFragmentPayload,
): Promise<boolean> {
return sendCommand<boolean>({
action: "fragments.update",
id,
payload,
});
}
export function deleteFragment(id: string): Promise<boolean> {
return sendCommand<boolean>({
action: "fragments.delete",
id,
});
}

View File

@ -0,0 +1,88 @@
import { sendCommand } from "./client";
import { pickCase } from "./normalize";
export type ListDocumentDto = {
id: string;
label: string;
content: string;
createdAt: string;
updatedAt: string;
};
export type CreateListPayload = {
label: string;
content?: string;
};
export type UpdateListPayload = {
label?: string;
content?: string;
};
type ListDocumentDtoRaw = {
id?: string;
label?: string;
content?: string;
createdAt?: string;
updatedAt?: string;
Id?: string;
Label?: string;
Content?: string;
CreatedAt?: string;
UpdatedAt?: string;
};
export function normalizeList(raw: ListDocumentDtoRaw): ListDocumentDto {
return {
id: pickCase(raw, "id", "Id", ""),
label: pickCase(raw, "label", "Label", ""),
content: pickCase(raw, "content", "Content", ""),
createdAt: pickCase(raw, "createdAt", "CreatedAt", ""),
updatedAt: pickCase(raw, "updatedAt", "UpdatedAt", ""),
};
}
export async function listLists(): Promise<ListDocumentDto[]> {
const data = await sendCommand<ListDocumentDtoRaw[]>({
action: "lists.list",
});
return data.map(normalizeList).filter((item) => Boolean(item.id));
}
export async function getList(id: string): Promise<ListDocumentDto | null> {
const data = await sendCommand<ListDocumentDtoRaw | null>({
action: "lists.get",
id,
});
if (!data) return null;
const normalized = normalizeList(data);
return normalized.id ? normalized : null;
}
export async function createList(
payload: CreateListPayload,
): Promise<ListDocumentDto> {
const data = await sendCommand<ListDocumentDtoRaw>({
action: "lists.create",
payload,
});
return normalizeList(data);
}
export function updateList(
id: string,
payload: UpdateListPayload,
): Promise<boolean> {
return sendCommand<boolean>({
action: "lists.update",
id,
payload,
});
}
export function deleteList(id: string): Promise<boolean> {
return sendCommand<boolean>({
action: "lists.delete",
id,
});
}

View File

@ -0,0 +1,20 @@
type UnknownObject = Record<string, unknown>;
function asObject(value: unknown): UnknownObject | undefined {
return value && typeof value === "object"
? (value as UnknownObject)
: undefined;
}
export function pickCase<T>(
source: unknown,
camelKey: string,
pascalKey: string,
fallback: T,
): T {
const obj = asObject(source);
if (!obj) return fallback;
const value = obj[camelKey] ?? obj[pascalKey];
return (value as T | undefined) ?? fallback;
}

View File

@ -0,0 +1,33 @@
import { invoke } from "$lib/runtime/invoke";
import {
startRecording as startMicRecording,
stopRecording as stopMicRecording,
} from "tauri-plugin-mic-recorder-api";
type SpeechControlResult = {
running: boolean;
pid?: number;
launch?: string;
};
export async function startSpeechDictation(): Promise<SpeechControlResult> {
return invoke<SpeechControlResult>("speech_start");
}
export async function stopSpeechDictation(): Promise<SpeechControlResult> {
return invoke<SpeechControlResult>("speech_stop");
}
export async function probeMicrophoneAccess(): Promise<string> {
await startMicRecording();
await new Promise((resolve) => setTimeout(resolve, 300));
const outputPath = await stopMicRecording();
try {
await invoke<{ deleted: boolean }>("speech_cleanup_probe", {
path: outputPath,
});
} catch {
// Keep probe non-blocking; cleanup failure should not break dictation start.
}
return outputPath;
}

View File

@ -0,0 +1,95 @@
import { sendCommand } from "./client";
import { pickCase } from "./normalize";
export type EntryTemplateItemDto = {
fileName: string;
filePath: string;
};
export type EntryTemplateLoadResultDto = {
fileName: string;
filePath: string;
content: string;
};
export type EntryTemplateSaveResultDto = {
filePath: string;
};
type EntryTemplateItemDtoRaw = {
fileName?: string;
filePath?: string;
FileName?: string;
FilePath?: string;
};
type EntryTemplateLoadResultDtoRaw = {
fileName?: string;
filePath?: string;
content?: string;
FileName?: string;
FilePath?: string;
Content?: string;
};
type EntryTemplateSaveResultDtoRaw = {
filePath?: string;
FilePath?: string;
};
function normalizeTemplateItem(
raw: EntryTemplateItemDtoRaw,
): EntryTemplateItemDto {
return {
fileName: pickCase(raw, "fileName", "FileName", ""),
filePath: pickCase(raw, "filePath", "FilePath", ""),
};
}
export async function listEntryTemplates(): Promise<EntryTemplateItemDto[]> {
const data = await sendCommand<EntryTemplateItemDtoRaw[]>({
action: "templates.list",
payload: {},
});
return data
.map(normalizeTemplateItem)
.filter((item) => Boolean(item.filePath));
}
export async function loadEntryTemplate(
filePath: string,
): Promise<EntryTemplateLoadResultDto> {
const data = await sendCommand<EntryTemplateLoadResultDtoRaw>({
action: "templates.load",
payload: { filePath },
});
return {
fileName: pickCase(data, "fileName", "FileName", ""),
filePath: pickCase(data, "filePath", "FilePath", ""),
content: pickCase(data, "content", "Content", ""),
};
}
export async function saveEntryTemplate(payload: {
name: string;
content: string;
filePath?: string;
}): Promise<EntryTemplateSaveResultDto> {
const data = await sendCommand<EntryTemplateSaveResultDtoRaw>({
action: "templates.save",
payload,
});
return {
filePath: pickCase(data, "filePath", "FilePath", ""),
};
}
export async function deleteEntryTemplate(filePath: string): Promise<boolean> {
return sendCommand<boolean>({
action: "templates.delete",
payload: { filePath },
});
}

View File

@ -0,0 +1,154 @@
import { sendCommand } from "./client";
import { pickCase } from "./normalize";
export type TodoItemDto = {
id: string;
listId: string;
text: string;
done: boolean;
sortOrder: number;
};
export type TodoListDto = {
id: string;
label: string;
createdAt: string;
items: TodoItemDto[];
};
export type CreateTodoListPayload = {
label: string;
};
export type UpdateTodoListPayload = {
label?: string;
};
export type CreateTodoItemPayload = {
listId: string;
text: string;
sortOrder?: number;
};
export type UpdateTodoItemPayload = {
text?: string;
done?: boolean;
sortOrder?: number;
};
type TodoItemDtoRaw = {
id?: string;
listId?: string;
text?: string;
done?: boolean;
sortOrder?: number;
Id?: string;
ListId?: string;
Text?: string;
Done?: boolean;
SortOrder?: number;
};
type TodoListDtoRaw = {
id?: string;
label?: string;
createdAt?: string;
items?: TodoItemDtoRaw[];
Id?: string;
Label?: string;
CreatedAt?: string;
Items?: TodoItemDtoRaw[];
};
function normalizeItem(raw: TodoItemDtoRaw): TodoItemDto {
return {
id: pickCase(raw, "id", "Id", ""),
listId: pickCase(raw, "listId", "ListId", ""),
text: pickCase(raw, "text", "Text", ""),
done: pickCase(raw, "done", "Done", false),
sortOrder: pickCase(raw, "sortOrder", "SortOrder", 0),
};
}
function normalizeList(raw: TodoListDtoRaw): TodoListDto {
const rawItems = pickCase(raw, "items", "Items", [] as TodoItemDtoRaw[]);
return {
id: pickCase(raw, "id", "Id", ""),
label: pickCase(raw, "label", "Label", ""),
createdAt: pickCase(raw, "createdAt", "CreatedAt", ""),
items: rawItems.map(normalizeItem),
};
}
export async function listTodoLists(): Promise<TodoListDto[]> {
const data = await sendCommand<TodoListDtoRaw[]>({
action: "todos.list",
});
return data.map(normalizeList).filter((item) => Boolean(item.id));
}
export async function getTodoList(id: string): Promise<TodoListDto | null> {
const data = await sendCommand<TodoListDtoRaw | null>({
action: "todos.get",
id,
});
if (!data) return null;
const normalized = normalizeList(data);
return normalized.id ? normalized : null;
}
export async function createTodoList(
payload: CreateTodoListPayload,
): Promise<TodoListDto> {
const data = await sendCommand<TodoListDtoRaw>({
action: "todos.create",
payload,
});
return normalizeList(data);
}
export function updateTodoList(
id: string,
payload: UpdateTodoListPayload,
): Promise<boolean> {
return sendCommand<boolean>({
action: "todos.update",
id,
payload,
});
}
export function deleteTodoList(id: string): Promise<boolean> {
return sendCommand<boolean>({
action: "todos.delete",
id,
});
}
export async function createTodoItem(
payload: CreateTodoItemPayload,
): Promise<TodoItemDto> {
const data = await sendCommand<TodoItemDtoRaw>({
action: "todos.items.create",
payload,
});
return normalizeItem(data);
}
export function updateTodoItem(
id: string,
payload: UpdateTodoItemPayload,
): Promise<boolean> {
return sendCommand<boolean>({
action: "todos.items.update",
id,
payload,
});
}
export function deleteTodoItem(id: string): Promise<boolean> {
return sendCommand<boolean>({
action: "todos.items.delete",
id,
});
}

View File

@ -0,0 +1,12 @@
export type BackendCommand = {
action: string;
correlationId?: string;
id?: string;
type?: string;
tag?: string;
payload?: unknown;
};
export type BackendOk<T> = { ok: true; data: T };
export type BackendErr = { ok: false; error: string };
export type BackendResponse<T> = BackendOk<T> | BackendErr;

View File

@ -0,0 +1,165 @@
<!-- @format -->
<script lang="ts">
import { createEventDispatcher } from "svelte";
export let open = false;
export let title = "";
export let message = "";
export let confirmText = "OK";
export let cancelText = "Cancel";
export let showCancel = false;
export let tone: "default" | "danger" = "default";
export let inputEnabled = false;
export let inputType = "text";
export let inputPlaceholder = "";
export let inputAriaLabel = "Modal input";
export let inputValue = "";
export let onConfirm: () => void = () => {};
export let onCancel: () => void = () => {};
const dispatch = createEventDispatcher<{ input: string }>();
function handleConfirm() {
onConfirm();
}
function handleCancel() {
onCancel();
}
function handleWindowKeydown(event: KeyboardEvent) {
if (!open) return;
if (event.key === "Escape") {
handleCancel();
}
if (event.key === "Enter") {
handleConfirm();
}
}
function handleInput(event: Event) {
const target = event.target as HTMLInputElement;
inputValue = target.value;
dispatch("input", inputValue);
}
</script>
<svelte:window on:keydown={handleWindowKeydown} />
{#if open}
<div class="modal-backdrop">
<dialog class="modal" open aria-label={title}>
<header class="modal-header">
<h2>{title}</h2>
</header>
<p class="modal-message">{message}</p>
{#if inputEnabled}
<input
class="modal-input"
type={inputType}
value={inputValue}
placeholder={inputPlaceholder}
aria-label={inputAriaLabel}
on:input={handleInput}
autofocus
/>
{/if}
<div class="modal-actions">
{#if showCancel}
<button type="button" class="secondary" on:click={handleCancel}
>{cancelText}</button
>
{/if}
<button
type="button"
class:danger={tone === "danger"}
on:click={handleConfirm}
>
{confirmText}
</button>
</div>
</dialog>
</div>
{/if}
<style>
.modal-backdrop {
position: fixed;
inset: 0;
background: rgba(7, 9, 12, 0.6);
backdrop-filter: blur(2px);
display: grid;
place-items: center;
z-index: 1000;
padding: 16px;
}
.modal {
position: static;
margin: 0;
width: min(420px, 100%);
border-radius: 12px;
border: 1px solid var(--border-strong);
background: var(--surface-1);
box-shadow: 0 18px 46px rgba(0, 0, 0, 0.45);
padding: 14px;
display: flex;
flex-direction: column;
gap: 10px;
}
.modal-header h2 {
font-size: 0.98rem;
color: var(--text-primary);
}
.modal-message {
color: var(--text-muted);
font-size: 0.86rem;
line-height: 1.45;
}
.modal-actions {
margin-top: 2px;
display: flex;
justify-content: flex-end;
gap: 8px;
}
.modal-input {
width: 100%;
border-radius: 8px;
border: 1px solid var(--border-soft);
background: var(--surface-2);
color: var(--text-primary);
font-size: 0.86rem;
padding: 9px 10px;
}
.modal-input::placeholder {
color: var(--text-dim);
}
.modal-actions button {
border-radius: 7px;
border: 1px solid var(--border-soft);
color: var(--text-primary);
background: var(--surface-2);
padding: 6px 11px;
font-size: 0.8rem;
cursor: pointer;
}
.modal-actions button.secondary {
background: var(--surface-1);
color: var(--text-muted);
}
.modal-actions button.danger {
border-color: var(--border-strong);
background: var(--surface-3);
color: var(--text-primary);
}
</style>

View File

@ -0,0 +1,319 @@
<!-- @format -->
<script lang="ts">
export let onVisibleMonthChange: (month: {
year: number;
month: number;
label: string;
}) => void = () => {};
export let onSelectedDateChange: (payload: {
year: number;
month: number;
day: number;
key: string;
}) => void = () => {};
export let onDateActivate: (payload: {
year: number;
month: number;
day: number;
key: string;
}) => void = () => {};
const today = new Date();
let currentYear = today.getFullYear();
let currentMonth = today.getMonth();
let selectedDateKey = getDateKey(
today.getFullYear(),
today.getMonth(),
today.getDate(),
);
const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
type CalendarCell = {
day: number;
month: number;
year: number;
inMonth: boolean;
isToday: boolean;
isSelected: boolean;
};
function getDateKey(year: number, month: number, day: number): string {
const mm = String(month + 1).padStart(2, "0");
const dd = String(day).padStart(2, "0");
return `${year}-${mm}-${dd}`;
}
function setViewDate(year: number, month: number) {
const next = new Date(year, month, 1);
currentYear = next.getFullYear();
currentMonth = next.getMonth();
}
function changeMonth(offset: number) {
setViewDate(currentYear, currentMonth + offset);
}
function selectCell(cell: CalendarCell) {
if (!cell.inMonth) {
setViewDate(cell.year, cell.month);
}
const key = getDateKey(cell.year, cell.month, cell.day);
selectedDateKey = key;
onDateActivate({
year: cell.year,
month: cell.month,
day: cell.day,
key,
});
}
function getCalendarCells(year: number, month: number): CalendarCell[] {
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const prevMonthLastDay = new Date(year, month, 0).getDate();
const startOffset = (firstDay.getDay() + 6) % 7;
const daysInMonth = lastDay.getDate();
const nextCells: CalendarCell[] = [];
for (let i = 0; i < startOffset; i += 1) {
const day = prevMonthLastDay - startOffset + i + 1;
const prevMonthDate = new Date(year, month - 1, day);
const key = getDateKey(
prevMonthDate.getFullYear(),
prevMonthDate.getMonth(),
day,
);
nextCells.push({
day,
month: prevMonthDate.getMonth(),
year: prevMonthDate.getFullYear(),
inMonth: false,
isToday:
key ===
getDateKey(today.getFullYear(), today.getMonth(), today.getDate()),
isSelected: key === selectedDateKey,
});
}
for (let day = 1; day <= daysInMonth; day += 1) {
const key = getDateKey(year, month, day);
nextCells.push({
day,
month,
year,
inMonth: true,
isToday:
key ===
getDateKey(today.getFullYear(), today.getMonth(), today.getDate()),
isSelected: key === selectedDateKey,
});
}
const trailing = (7 - (nextCells.length % 7)) % 7;
for (let day = 1; day <= trailing; day += 1) {
const nextMonthDate = new Date(year, month + 1, day);
const key = getDateKey(
nextMonthDate.getFullYear(),
nextMonthDate.getMonth(),
day,
);
nextCells.push({
day,
month: nextMonthDate.getMonth(),
year: nextMonthDate.getFullYear(),
inMonth: false,
isToday:
key ===
getDateKey(today.getFullYear(), today.getMonth(), today.getDate()),
isSelected: key === selectedDateKey,
});
}
return nextCells;
}
$: monthLabel = new Date(currentYear, currentMonth, 1).toLocaleString(
undefined,
{ month: "long" },
);
$: cells = getCalendarCells(currentYear, currentMonth);
$: onVisibleMonthChange({
year: currentYear,
month: currentMonth,
label: monthLabel,
});
$: {
const parts = selectedDateKey.split("-");
const [year, month, day] = parts.map((value) => Number(value));
if (
parts.length === 3 &&
!Number.isNaN(year) &&
!Number.isNaN(month) &&
!Number.isNaN(day)
) {
onSelectedDateChange({
year,
month: month - 1,
day,
key: selectedDateKey,
});
}
}
</script>
<section class="calendar-widget" aria-label="Monthly calendar">
<header class="calendar-header">
<button
type="button"
class="nav-icon"
aria-label="Previous month"
on:click={() => changeMonth(-1)}
>
<span class="material-symbols-outlined">chevron_left</span>
</button>
<div class="month-title">
<h3>{monthLabel}</h3>
<span>{currentYear}</span>
</div>
<button
type="button"
class="nav-icon"
aria-label="Next month"
on:click={() => changeMonth(1)}
>
<span class="material-symbols-outlined">chevron_right</span>
</button>
</header>
<div class="calendar-weekdays">
{#each weekdays as weekday}
<span>{weekday}</span>
{/each}
</div>
<div class="calendar-grid">
{#each cells as cell}
<button
type="button"
class="calendar-cell"
class:is-muted={!cell.inMonth}
class:is-today={cell.isToday}
class:is-selected={cell.isSelected}
aria-label={`Day ${cell.day}`}
on:click={() => selectCell(cell)}
>
<span class="day-number">{cell.day}</span>
</button>
{/each}
</div>
</section>
<style>
.calendar-widget {
display: flex;
flex-direction: column;
gap: 10px;
border: 1px solid var(--border-soft);
border-radius: 10px;
background: var(--surface-1);
padding: 10px;
}
.calendar-header {
display: grid;
grid-template-columns: 28px minmax(0, 1fr) 28px;
align-items: center;
gap: 8px;
}
.nav-icon {
width: 28px;
height: 28px;
border: 1px solid var(--border-soft);
border-radius: 6px;
display: grid;
place-items: center;
color: var(--text-muted);
cursor: pointer;
}
.nav-icon .material-symbols-outlined {
font-size: 1rem;
}
.nav-icon:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.month-title {
text-align: center;
}
.month-title h3 {
font-size: 0.86rem;
font-weight: 600;
color: var(--text-primary);
}
.month-title span {
font-size: 0.74rem;
color: var(--text-muted);
}
.calendar-weekdays,
.calendar-grid {
display: grid;
grid-template-columns: repeat(7, minmax(0, 1fr));
gap: 4px;
}
.calendar-weekdays span {
text-align: center;
font-size: 0.7rem;
color: var(--text-dim);
font-weight: 500;
}
.calendar-cell {
height: 36px;
border-radius: 7px;
border: 1px solid transparent;
font-size: 0.76rem;
color: var(--text-muted);
cursor: pointer;
position: relative;
display: flex;
align-items: center;
justify-content: center;
}
.day-number {
line-height: 1;
}
.calendar-cell:hover {
color: var(--text-primary);
background: var(--bg-hover);
border-color: var(--border-soft);
}
.calendar-cell.is-muted {
color: var(--text-dim);
}
.calendar-cell.is-today {
color: var(--text-primary);
background: var(--surface-3);
border-color: var(--border-strong);
}
.calendar-cell.is-selected {
border-color: var(--zinc-300);
box-shadow: inset 0 0 0 1px var(--zinc-300);
}
</style>

View File

@ -0,0 +1,706 @@
<!-- @format -->
<script lang="ts">
import type { AiHealthDto, CoachPlanDto } from "$lib/backend/ai";
import {
activeConversationStore,
sendConversationMessage,
clearActiveConversation,
} from "$lib/stores/conversations";
export let health: AiHealthDto | null = null;
export let healthChecking = false;
export let coachBusy = false;
export let coachError = "";
export let coachPlan: CoachPlanDto | null = null;
export let coachKind = "";
$: chatBusy = $activeConversationStore.busy;
$: chatMessages = $activeConversationStore.messages;
let chatInput = "";
function handleChatSubmit() {
const prompt = chatInput.trim();
if (!prompt) return;
chatInput = "";
void sendConversationMessage(prompt);
}
function handleChatKeydown(event: KeyboardEvent) {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
handleChatSubmit();
}
}
const kindLabels: Record<string, string> = {
daily: "Daily Check-In",
daily_checkin: "Daily Check-In",
evening: "Evening Review",
evening_review: "Evening Review",
weekly: "Weekly Review",
weekly_review: "Weekly Review",
};
</script>
<div class="coach-panel">
<!-- Health banner -->
<div
class="health-banner"
class:is-healthy={health?.healthy}
class:is-unhealthy={health && !health.healthy}
>
{#if healthChecking}
<span class="health-dot checking"></span>
<span class="health-label">Checking AI status…</span>
{:else if health}
<span
class="health-dot"
class:healthy={health.healthy}
class:unhealthy={!health.healthy}
></span>
<span class="health-label">
{health.provider || "AI"}{health.healthy ? "Ready" : "Unavailable"}
</span>
{#if health.message}
<span class="health-message">{health.message}</span>
{/if}
{:else}
<span class="health-dot unknown"></span>
<span class="health-label">AI status unknown</span>
{/if}
</div>
<!-- Coach result -->
{#if coachBusy}
<div class="coach-loading">
<div class="spinner"></div>
<p>Running {kindLabels[coachKind] ?? "coach session"}</p>
<p class="loading-hint">
This may take a moment while the model generates a response.
</p>
</div>
{:else if coachError}
<div class="coach-error">
<span class="material-symbols-outlined error-icon">error</span>
<p>{coachError}</p>
</div>
{:else if coachPlan}
<article class="coach-plan">
<header class="plan-header">
<span class="plan-kind"
>{kindLabels[coachPlan.kind] ?? coachPlan.kind}</span
>
<h2>{coachPlan.title}</h2>
</header>
{#if coachPlan.summary}
<section class="plan-section">
<h3>Summary</h3>
<p>{coachPlan.summary}</p>
</section>
{/if}
{#if coachPlan.questions.length > 0}
<section class="plan-section">
<h3>Reflection Questions</h3>
<ol class="plan-list">
{#each coachPlan.questions as question}
<li>{question}</li>
{/each}
</ol>
</section>
{/if}
{#if coachPlan.suggestedNextActions.length > 0}
<section class="plan-section">
<h3>Suggested Next Actions</h3>
<ul class="plan-list">
{#each coachPlan.suggestedNextActions as action}
<li>{action}</li>
{/each}
</ul>
</section>
{/if}
{#if coachPlan.suggestedTags.length > 0}
<section class="plan-section">
<h3>Suggested Tags</h3>
<div class="tag-list">
{#each coachPlan.suggestedTags as tag}
<span class="tag">{tag}</span>
{/each}
</div>
</section>
{/if}
{#if coachPlan.evidence.length > 0}
<section class="plan-section">
<h3>Evidence</h3>
<ul class="evidence-list">
{#each coachPlan.evidence as item}
<li>
<span class="evidence-text">{item.text}</span>
{#if item.recordId}
<span class="evidence-ref">({item.recordId})</span>
{/if}
</li>
{/each}
</ul>
</section>
{/if}
{#if coachPlan.patchProposal}
<section class="plan-section">
<h3>Patch Proposal</h3>
<div class="patch-proposal">
<span class="patch-kind">{coachPlan.patchProposal.kind}</span>
{#if coachPlan.patchProposal.description}
<p>{coachPlan.patchProposal.description}</p>
{/if}
{#if coachPlan.patchProposal.content}
<pre class="patch-content">{coachPlan.patchProposal.content}</pre>
{/if}
</div>
</section>
{/if}
</article>
{:else if chatMessages.length === 0 && !chatBusy}
<div class="coach-empty">
<span class="material-symbols-outlined empty-icon">psychology</span>
<p>
Select a coaching session from the sidebar, or ask a question using the
input below.
</p>
</div>
{/if}
<!-- Chat conversation -->
{#if chatMessages.length > 0}
<section class="chat-history">
<h3>Conversation</h3>
<div class="chat-messages">
{#each chatMessages as msg}
<div
class="chat-msg"
class:chat-user={msg.role === "user"}
class:chat-assistant={msg.role === "assistant"}
class:chat-error={msg.role === "error"}
>
<span class="chat-role"
>{msg.role === "user"
? "You"
: msg.role === "error"
? "Error"
: "AI"}</span
>
<div class="chat-text">{msg.text}</div>
</div>
{/each}
{#if chatBusy}
<div class="chat-msg chat-assistant">
<span class="chat-role">AI</span>
<div class="chat-thinking">
<div class="spinner-sm"></div>
<span>Thinking…</span>
</div>
</div>
{/if}
</div>
</section>
{:else if chatBusy}
<div class="chat-loading">
<div class="spinner"></div>
<p>Thinking…</p>
</div>
{/if}
<!-- Chat input (pinned at bottom) -->
<div class="chat-input-bar">
<div class="chat-input-row">
<input
type="text"
bind:value={chatInput}
placeholder="Ask a question…"
on:keydown={handleChatKeydown}
disabled={chatBusy}
/>
<button
type="button"
class="chat-send-btn"
on:click={handleChatSubmit}
disabled={chatBusy || !chatInput.trim()}
aria-label="Send"
>
<span class="material-symbols-outlined">send</span>
</button>
</div>
{#if chatMessages.length > 0}
<button
type="button"
class="chat-clear-btn"
on:click={clearActiveConversation}
>
Clear Chat
</button>
{/if}
</div>
</div>
<style>
.coach-panel {
display: flex;
flex-direction: column;
gap: 20px;
padding: 24px 24px 0;
overflow: auto;
min-height: 0;
flex: 1;
}
/* ── Health banner ───────────────────────────────── */
.health-banner {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 14px;
border-radius: 10px;
border: 1px solid var(--border-soft);
background: var(--surface-1);
font-size: 0.82rem;
}
.health-dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
&.healthy {
background: #4ade80;
}
&.unhealthy {
background: #e06c75;
}
&.checking {
background: var(--text-dim);
animation: pulse 1s ease-in-out infinite;
}
&.unknown {
background: var(--text-dim);
}
}
.health-label {
color: var(--text-primary);
font-weight: 500;
}
.health-message {
color: var(--text-dim);
margin-left: auto;
}
/* ── Coach plan ──────────────────────────────────── */
.coach-plan {
display: flex;
flex-direction: column;
gap: 18px;
}
.plan-header {
display: flex;
flex-direction: column;
gap: 4px;
h2 {
font-size: 1.15rem;
font-weight: 600;
color: var(--text-primary);
}
}
.plan-kind {
font-size: 0.72rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-dim);
}
.plan-section {
display: flex;
flex-direction: column;
gap: 8px;
h3 {
font-size: 0.82rem;
font-weight: 600;
color: var(--text-muted);
letter-spacing: 0.01em;
}
p {
font-size: 0.88rem;
color: var(--text-primary);
line-height: 1.55;
}
}
.plan-list {
display: flex;
flex-direction: column;
gap: 6px;
padding-left: 20px;
li {
font-size: 0.86rem;
color: var(--text-primary);
line-height: 1.5;
}
}
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.tag {
padding: 3px 10px;
border-radius: 20px;
border: 1px solid var(--border-soft);
background: var(--surface-2);
font-size: 0.76rem;
color: var(--text-muted);
}
.evidence-list {
display: flex;
flex-direction: column;
gap: 6px;
list-style: none;
li {
padding: 8px 12px;
border-radius: 8px;
border: 1px solid var(--border-soft);
background: var(--surface-1);
font-size: 0.84rem;
line-height: 1.45;
}
}
.evidence-text {
color: var(--text-primary);
}
.evidence-ref {
color: var(--text-dim);
font-size: 0.76rem;
margin-left: 6px;
}
.patch-proposal {
padding: 12px;
border-radius: 8px;
border: 1px solid var(--border-soft);
background: var(--surface-1);
display: flex;
flex-direction: column;
gap: 8px;
p {
font-size: 0.84rem;
color: var(--text-primary);
line-height: 1.5;
}
}
.patch-kind {
font-size: 0.72rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--text-dim);
}
.patch-content {
font-family: "Cascadia Code", "Fira Code", monospace;
font-size: 0.8rem;
color: var(--text-muted);
background: var(--surface-2);
padding: 10px 12px;
border-radius: 6px;
border: 1px solid var(--border-soft);
overflow-x: auto;
white-space: pre-wrap;
word-break: break-word;
}
/* ── Chat conversation ────────────────────────────── */
.chat-history {
display: flex;
flex-direction: column;
gap: 10px;
border-top: 1px solid var(--border-soft);
padding-top: 18px;
h3 {
font-size: 0.82rem;
font-weight: 600;
color: var(--text-muted);
}
}
.chat-messages {
display: flex;
flex-direction: column;
gap: 8px;
}
.chat-msg {
display: flex;
flex-direction: column;
gap: 4px;
padding: 10px 14px;
border-radius: 10px;
border: 1px solid var(--border-soft);
}
.chat-user {
background: var(--surface-2);
align-self: flex-end;
max-width: 85%;
}
.chat-assistant {
background: var(--surface-1);
align-self: flex-start;
max-width: 85%;
}
.chat-error {
background: rgba(224, 108, 117, 0.08);
border-color: #e06c75;
align-self: flex-start;
max-width: 85%;
}
.chat-role {
font-size: 0.7rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--text-dim);
}
.chat-error .chat-role {
color: #e06c75;
}
.chat-text {
font-size: 0.86rem;
color: var(--text-primary);
line-height: 1.55;
white-space: pre-wrap;
word-break: break-word;
}
.chat-thinking {
display: flex;
align-items: center;
gap: 8px;
font-size: 0.82rem;
color: var(--text-dim);
}
.spinner-sm {
width: 16px;
height: 16px;
border: 2px solid var(--border-soft);
border-top-color: var(--text-muted);
border-radius: 50%;
animation: spin 0.7s linear infinite;
}
/* ── Empty / loading / error ─────────────────────── */
.coach-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
padding: 60px 20px;
text-align: center;
.empty-icon {
font-size: 2.8rem;
color: var(--text-dim);
}
p {
font-size: 0.88rem;
color: var(--text-dim);
max-width: 320px;
}
}
.coach-loading,
.chat-loading {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 40px 20px;
text-align: center;
p {
font-size: 0.88rem;
color: var(--text-muted);
}
}
.loading-hint {
font-size: 0.78rem !important;
color: var(--text-dim) !important;
}
.coach-error {
display: flex;
align-items: flex-start;
gap: 8px;
padding: 12px 14px;
border-radius: 10px;
border: 1px solid #e06c75;
background: rgba(224, 108, 117, 0.08);
.error-icon {
color: #e06c75;
font-size: 1.1rem;
flex-shrink: 0;
margin-top: 1px;
}
p {
font-size: 0.84rem;
color: var(--text-primary);
line-height: 1.45;
}
}
.spinner {
width: 28px;
height: 28px;
border: 3px solid var(--border-soft);
border-top-color: var(--text-muted);
border-radius: 50%;
animation: spin 0.7s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@keyframes pulse {
0%,
100% {
opacity: 0.4;
}
50% {
opacity: 1;
}
}
/* ── Chat input bar (pinned bottom) ─────────────── */
.chat-input-bar {
position: sticky;
bottom: 0;
display: flex;
flex-direction: column;
gap: 6px;
padding: 12px 0 24px;
background: var(--bg-editor);
margin-top: auto;
}
.chat-input-row {
display: flex;
align-items: center;
gap: 6px;
border: 1px solid var(--border-soft);
border-radius: 10px;
background: var(--surface-1);
padding: 6px 8px 6px 14px;
input {
flex: 1;
min-width: 0;
font-size: 0.86rem;
color: var(--text-primary);
&::placeholder {
color: var(--text-dim);
}
&:disabled {
opacity: 0.5;
}
}
}
.chat-send-btn {
width: 32px;
height: 32px;
display: grid;
place-items: center;
border-radius: 8px;
color: var(--text-muted);
cursor: pointer;
border: 1px solid transparent;
flex-shrink: 0;
.material-symbols-outlined {
font-size: 1rem;
}
&:hover {
background: var(--bg-hover);
border-color: var(--border-soft);
color: var(--text-primary);
}
&:disabled {
opacity: 0.4;
cursor: default;
}
}
.chat-clear-btn {
align-self: flex-start;
padding: 4px 10px;
border-radius: 6px;
border: 1px solid var(--border-soft);
background: transparent;
color: var(--text-dim);
font-size: 0.74rem;
cursor: pointer;
&:hover {
color: var(--text-primary);
border-color: var(--border-strong);
background: var(--bg-hover);
}
}
</style>

View File

@ -0,0 +1,380 @@
<!-- @format -->
<script lang="ts">
import FragmentEditor from "$lib/components/editor/FragmentEditor.svelte";
import ListEditor from "$lib/components/editor/ListEditor.svelte";
import TodoEditor from "$lib/components/editor/TodoEditor.svelte";
import MarkdownEditor from "$lib/components/editor/MarkdownEditor.svelte";
import CoachPanel from "$lib/components/CoachPanel.svelte";
import { aiStatusStore, coachStateStore } from "$lib/stores/ai";
export let activeSection = "entries";
export let openDocumentId = "entries/daily-notes";
export let openDocumentName = "Daily Notes";
export let openDocumentContent = "";
export let onDocumentContentChange: (content: string) => void = () => {};
export let onOpenDocument: (doc: {
id: string;
label: string;
initialContent: string;
linkedFrom?: {
id: string;
label: string;
initialContent: string;
section: "entries" | "fragments" | "todos" | "lists" | "calendar";
};
}) => void = () => {};
export let onDeleteDocument: (id: string) => void = () => {};
export let showLinkedBackButton = false;
export let onLinkedBack: () => void = () => {};
export let calendarItems: Array<{
id: string;
label: string;
initialContent: string;
}> = [];
export let calendarBusy = false;
export let calendarError = "";
export let previewOnly = true;
export let onForceSave: () => Promise<void> | void = () => {};
type CalendarCard = {
id: string;
label: string;
initialContent: string;
title: string;
summary: string;
hasTrigger: boolean;
hasMood: boolean;
hasOpenTodos: boolean;
};
function deriveSummary(content: string): string {
const lines = content.replace(/\r\n/g, "\n").split("\n");
let inFrontmatter = false;
let frontmatterDone = false;
for (const rawLine of lines) {
const line = rawLine.trim();
if (!frontmatterDone && line === "---") {
inFrontmatter = !inFrontmatter;
if (!inFrontmatter) frontmatterDone = true;
continue;
}
if (inFrontmatter || !line) continue;
if (/^#/.test(line)) continue;
if (/^\*\*Date:\*\*/i.test(line)) continue;
if (/^Date:/i.test(line)) continue;
if (/^(Type:|Tags:)/i.test(line)) continue;
return line.length > 180 ? `${line.slice(0, 177)}...` : line;
}
return "No summary available.";
}
function deriveTitle(label: string, content: string): string {
const heading = content.match(/^#\s+(.+)$/m)?.[1]?.trim();
if (heading) return heading;
return label?.trim() || "Untitled Entry";
}
function toCalendarCard(item: {
id: string;
label: string;
initialContent: string;
}): CalendarCard {
const content = item.initialContent ?? "";
const lower = content.toLowerCase();
return {
...item,
title: deriveTitle(item.label, content),
summary: deriveSummary(content),
hasTrigger:
lower.includes("!trigger") ||
lower.includes("#trigger") ||
lower.includes("#stress"),
hasMood:
lower.includes("mental / emotional snapshot") ||
lower.includes("cognitive state"),
hasOpenTodos: /-\s*\[\s\]/.test(content),
};
}
$: calendarCards = calendarItems.map(toCalendarCard);
</script>
<main class="editor-panel" aria-label="Editor area">
{#if showLinkedBackButton}
<div class="editor-nav">
<button
type="button"
class="back-btn"
on:click={onLinkedBack}
aria-label="Back to source entry"
>
<span class="material-symbols-outlined" aria-hidden="true"
>arrow_back</span
>
</button>
</div>
{/if}
{#if activeSection === "calendar"}
<section class="calendar-main" aria-label="Calendar timeline results">
<header class="calendar-main-header">
<h2>Filtered Entries</h2>
</header>
{#if calendarBusy}
<p class="calendar-copy">Loading timeline...</p>
{:else if calendarError}
<p class="calendar-copy is-error">{calendarError}</p>
{:else if calendarItems.length === 0}
<p class="calendar-copy">No entries matched the current filters.</p>
{:else}
<ul class="calendar-list">
{#each calendarCards as item}
<li class:is-active={item.id === openDocumentId}>
<button
type="button"
class="calendar-item-btn"
on:click={() => onOpenDocument(item)}
>
<div class="calendar-item-head">
<h3>{item.title}</h3>
<span class="calendar-date">{item.label}</span>
</div>
<p class="calendar-summary">{item.summary}</p>
<div class="calendar-badges">
{#if item.hasMood}<span class="badge mood">Mood</span>{/if}
{#if item.hasTrigger}<span class="badge trigger">Trigger</span
>{/if}
{#if item.hasOpenTodos}<span class="badge todo"
>Open To-Dos</span
>{/if}
</div>
</button>
</li>
{/each}
</ul>
{/if}
</section>
{:else if activeSection === "coach"}
<CoachPanel
health={$aiStatusStore.health}
healthChecking={$aiStatusStore.checking}
coachBusy={$coachStateStore.busy}
coachError={$coachStateStore.error}
coachPlan={$coachStateStore.plan}
coachKind={$coachStateStore.kind}
/>
{:else if !openDocumentId}
<div class="editor-empty">
<span class="material-symbols-outlined empty-icon">edit_note</span>
<p>Select or create an item to get started</p>
</div>
{:else if activeSection === "fragments"}
<FragmentEditor
{openDocumentId}
{openDocumentName}
{openDocumentContent}
{onDocumentContentChange}
{onOpenDocument}
{onDeleteDocument}
externalEditRequested={!previewOnly}
/>
{:else if activeSection === "todos"}
<TodoEditor
{openDocumentId}
{openDocumentName}
{openDocumentContent}
{onDocumentContentChange}
/>
{:else if activeSection === "lists"}
<ListEditor
{openDocumentId}
{openDocumentName}
{openDocumentContent}
{onDocumentContentChange}
/>
{:else}
<MarkdownEditor
{openDocumentId}
{openDocumentName}
{openDocumentContent}
{onDocumentContentChange}
{onForceSave}
{onOpenDocument}
{previewOnly}
/>
{/if}
</main>
<style>
.editor-panel {
background: var(--bg-editor);
padding: 18px 20px;
display: flex;
flex-direction: column;
gap: 16px;
min-height: 0;
overflow: hidden;
}
.editor-nav {
display: flex;
align-items: center;
justify-content: flex-start;
}
.back-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
border-radius: 8px;
border: 1px solid var(--border-soft);
background: color-mix(in srgb, var(--surface-1) 90%, var(--bg-editor) 10%);
color: var(--text-primary);
padding: 0;
cursor: pointer;
}
.back-btn:hover {
background: var(--bg-hover);
}
.editor-empty {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
color: var(--text-dim);
.empty-icon {
font-size: 2.4rem;
opacity: 0.5;
}
p {
font-size: 0.88rem;
}
}
.calendar-main {
flex: 1;
min-height: 0;
overflow: auto;
padding: 4px 8px;
display: flex;
flex-direction: column;
gap: 10px;
}
.calendar-main-header h2 {
font-size: 0.96rem;
font-weight: 600;
color: var(--text-primary);
}
.calendar-copy {
font-size: 0.84rem;
color: var(--text-dim);
}
.calendar-copy.is-error {
color: #e74c3c;
}
.calendar-list {
list-style: none;
display: flex;
flex-direction: column;
gap: 6px;
}
.calendar-list li {
border-radius: 8px;
border: 1px solid var(--border-soft);
background: color-mix(in srgb, var(--surface-1) 92%, var(--bg-editor) 8%);
}
.calendar-list li:hover {
background: var(--bg-hover);
}
.calendar-list li.is-active {
border-color: var(--border-strong);
background: var(--bg-active);
}
.calendar-item-btn {
width: 100%;
text-align: left;
padding: 10px 12px;
color: var(--text-primary);
font-size: 0.86rem;
cursor: pointer;
display: flex;
flex-direction: column;
gap: 7px;
}
.calendar-item-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
.calendar-item-head h3 {
font-size: 0.9rem;
font-weight: 600;
color: var(--text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.calendar-date {
font-size: 0.74rem;
color: var(--text-dim);
white-space: nowrap;
}
.calendar-summary {
font-size: 0.82rem;
color: var(--text-muted);
line-height: 1.45;
}
.calendar-badges {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.badge {
font-size: 0.68rem;
border-radius: 999px;
border: 1px solid var(--border-soft);
padding: 2px 7px;
color: var(--text-dim);
background: color-mix(in srgb, var(--surface-2) 88%, var(--bg-editor) 12%);
}
.badge.mood {
border-color: color-mix(in srgb, #6ba7ff 40%, var(--border-soft) 60%);
color: #8dbbff;
}
.badge.trigger {
border-color: color-mix(in srgb, #f08c6c 40%, var(--border-soft) 60%);
color: #f5ad95;
}
.badge.todo {
border-color: color-mix(in srgb, #f2c266 40%, var(--border-soft) 60%);
color: #f4d690;
}
</style>

View File

@ -0,0 +1,194 @@
<!-- @format -->
<script lang="ts">
export let activeSection: string | null = "entries";
export let onSelect: (id: string) => void = () => {};
type NavItem = {
id: string;
label: string;
icon: string;
};
const workspaceItems: NavItem[] = [
{ id: "entries", label: "Entries", icon: "menu_book" },
{ id: "calendar", label: "Calendar", icon: "calendar_month" },
{ id: "fragments", label: "Fragments", icon: "auto_stories" },
{ id: "todos", label: "To-Do List", icon: "checklist" },
{ id: "lists", label: "Lists", icon: "lists" },
{ id: "coach", label: "Coach", icon: "psychology" },
];
function selectItem(id: string) {
onSelect(id);
}
</script>
<aside class="navbar" aria-label="Primary navigation">
<div class="navbar-header">
<img src="icon.png" alt="Journal logo" style="height: 48px; width: 48px;" />
</div>
<nav class="nav-groups" aria-label="Journal sections">
<div class="nav-group">
{#each workspaceItems as item}
<button
type="button"
class="nav-button"
class:is-active={activeSection === item.id}
on:click={() => selectItem(item.id)}
aria-label={item.label}
>
<span class="material-symbols-outlined">{item.icon}</span>
<span class="nav-tooltip" role="tooltip">{item.label}</span>
</button>
{/each}
</div>
</nav>
<button
type="button"
class="settings-chip"
class:is-active={activeSection === "settings"}
aria-label="Settings"
on:click={() => selectItem("settings")}
>
<span class="material-symbols-outlined">settings</span>
<span class="nav-tooltip" role="tooltip">Settings</span>
</button>
</aside>
<style>
.navbar {
position: relative;
z-index: 20;
display: flex;
flex-direction: column;
align-items: center;
gap: 14px;
padding: 14px 10px;
background: linear-gradient(
180deg,
var(--surface-2) 0%,
var(--bg-navbar) 100%
);
border-right: 1px solid var(--border-soft);
}
.navbar-header img {
width: 34px;
height: 34px;
object-fit: cover;
border-radius: 9px;
border: 1px solid var(--border-strong);
display: block;
}
.nav-groups {
width: 100%;
display: flex;
flex-direction: column;
gap: 10px;
}
.nav-group {
display: flex;
flex-direction: column;
gap: 4px;
align-items: center;
}
.nav-button,
.settings-chip {
position: relative;
width: 44px;
height: 44px;
display: grid;
place-items: center;
border-radius: 10px;
color: var(--text-dim);
border: 1px solid transparent;
cursor: pointer;
transition:
background-color 0.14s ease,
color 0.14s ease,
border-color 0.14s ease;
}
.nav-button .material-symbols-outlined {
font-size: 1.18rem;
}
.settings-chip .material-symbols-outlined {
font-size: 1.18rem;
}
.nav-tooltip {
position: absolute;
left: calc(100% + 12px);
top: 50%;
transform: translateY(-50%) translateX(-4px);
opacity: 0;
pointer-events: none;
white-space: nowrap;
padding: 4px 9px;
border-radius: 6px;
font-size: 0.76rem;
font-weight: 500;
color: var(--text-primary);
background: var(--surface-1);
border: 1px solid var(--border-strong);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);
transition:
opacity 0.12s ease,
transform 0.12s ease;
}
.nav-button:hover,
.nav-button:focus-visible,
.settings-chip:hover,
.settings-chip:focus-visible {
color: var(--text-primary);
background: var(--bg-hover);
border-color: var(--border-soft);
}
.nav-button:hover .nav-tooltip,
.nav-button:focus-visible .nav-tooltip,
.settings-chip:hover .nav-tooltip,
.settings-chip:focus-visible .nav-tooltip {
opacity: 1;
transform: translateY(-50%) translateX(0);
}
.nav-button.is-active {
color: var(--text-primary);
background: var(--bg-active);
border-color: var(--border-strong);
}
.nav-button.is-active .material-symbols-outlined {
color: var(--accent);
}
.settings-chip {
margin-top: auto;
}
.settings-chip.is-active {
color: var(--text-primary);
background: var(--bg-active);
border-color: var(--border-strong);
}
.settings-chip.is-active .material-symbols-outlined {
color: var(--accent);
}
@media (max-width: 980px) {
.nav-button,
.settings-chip {
width: 40px;
height: 40px;
}
}
</style>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,708 @@
<!-- @format -->
<script lang="ts">
import {
probeMicrophoneAccess,
startSpeechDictation,
stopSpeechDictation,
} from "$lib/backend/speech";
import { isTauriRuntime } from "$lib/runtime/invoke";
import {
createFragmentFromParsed,
deleteFragmentByStoreId,
fragmentsStore,
hasFragment,
parseFragmentContent,
serializeFragment,
updateFragmentFromParsed,
type FragmentItem,
} from "$lib/stores/fragments";
import { settingsFragmentTypes, settingsTags } from "$lib/stores/settings";
import { renderMarkdown } from "$lib/utils/markdown";
import { onDestroy, onMount } from "svelte";
import { get } from "svelte/store";
export let openDocumentId = "";
export let openDocumentName = "";
export let openDocumentContent = "";
export let onDocumentContentChange: (content: string) => void = () => {};
export let onOpenDocument: (doc: {
id: string;
label: string;
initialContent: string;
}) => void = () => {};
export let onDeleteDocument: (id: string) => void = () => {};
export let externalEditRequested = false;
let fragmentTitle = "";
let fragmentType = "";
let customFragmentType = "";
let fragmentTag = "";
let customFragmentTags = "";
let fragmentBody = "";
let fragmentMode: "view" | "edit" | "create" = "view";
let lastFragmentDocumentId = "";
let fragmentTypeOptions: string[] = [];
let tagOptions: string[] = [];
let suppressExternalEditRequest = false;
let dictationBusy = false;
let dictationActive = false;
let dictationError = "";
let dictationStatus = "";
let unlistenTranscript: (() => void) | null = null;
let unlistenSpeechStatus: (() => void) | null = null;
const customTypeValue = "__custom_type__";
const customTagValue = "__custom_tag__";
function buildFragmentContent(): {
title: string;
resolvedType: string;
body: string;
content: string;
tags: string[];
} | null {
const title = fragmentTitle.trim();
if (!title) return null;
const resolvedType =
fragmentType === customTypeValue
? customFragmentType.trim()
: fragmentType;
if (!resolvedType) return null;
const selectedTags =
fragmentTag && fragmentTag !== customTagValue ? [fragmentTag] : [];
const customTags = customFragmentTags
.split(",")
.map((tag) => tag.trim())
.filter(Boolean);
const tagList = [...selectedTags, ...customTags];
const uniqueTagList = [
...new Set(tagList.map((tag) => tag.toLowerCase())),
].map((lower) => {
return tagList.find((tag) => tag.toLowerCase() === lower) ?? lower;
});
const body = fragmentBody.trim() || "Add details for this fragment.";
const content = serializeFragment({
title,
type: resolvedType,
tags: uniqueTagList,
body,
});
return { title, resolvedType, body, content, tags: uniqueTagList };
}
async function saveFragmentEdits() {
try {
const payload = buildFragmentContent();
if (!payload) return;
const exists = hasFragment(openDocumentId);
if (!exists) {
await createNewFragment();
return;
}
const updated = await updateFragmentFromParsed(openDocumentId, {
title: payload.title,
type: payload.resolvedType,
tags: payload.tags,
body: payload.body,
});
if (!updated) return;
onDocumentContentChange(payload.content);
fragmentMode = "view";
} catch (error) {
console.error("[editor] fragment:save:error", error);
}
}
async function createNewFragment() {
try {
const payload = buildFragmentContent();
if (!payload) return;
const item: FragmentItem = await createFragmentFromParsed({
title: payload.title,
type: payload.resolvedType,
tags: payload.tags,
body: payload.body,
});
onOpenDocument(item);
fragmentMode = "view";
} catch (error) {
console.error("[editor] fragment:create:error", error);
}
}
async function deleteCurrentFragment() {
try {
const ok = await deleteFragmentByStoreId(openDocumentId);
if (!ok) return;
const remaining = get(fragmentsStore);
onDeleteDocument(openDocumentId);
if (remaining.length > 0) {
onOpenDocument(remaining[0]);
fragmentMode = "view";
return;
}
fragmentTitle = "";
customFragmentType = "";
fragmentTag = customTagValue;
customFragmentTags = "";
fragmentBody = "";
fragmentMode = "create";
} catch (error) {
console.error("[editor] fragment:delete:error", error);
}
}
function startEditFragment() {
fragmentMode = "edit";
}
function cancelFragmentEdit() {
if (dictationActive) {
void stopDictation();
}
if (fragmentMode === "create") {
fragmentMode = "view";
suppressExternalEditRequest = true;
return;
}
loadFragmentFormFromDocument();
fragmentMode = "view";
suppressExternalEditRequest = true;
}
function loadFragmentFormFromDocument() {
const content = openDocumentContent ?? "";
const isDraftFragment = openDocumentId.startsWith("fragments/new-");
const parsed = parseFragmentContent(
content,
openDocumentName || "Untitled Fragment",
);
fragmentTitle = parsed.title;
const parsedType = parsed.type;
if (!parsedType) {
fragmentType = fragmentTypeOptions[0] ?? customTypeValue;
customFragmentType = "";
} else if (fragmentTypeOptions.includes(parsedType)) {
fragmentType = parsedType;
customFragmentType = "";
} else {
fragmentType = customTypeValue;
customFragmentType = parsedType;
}
const parsedTags = parsed.tags;
if (parsedTags.length === 0) {
fragmentTag = tagOptions[0] ?? customTagValue;
customFragmentTags = "";
} else {
const primary = parsedTags[0];
if (tagOptions.includes(primary)) {
fragmentTag = primary;
customFragmentTags = parsedTags.slice(1).join(", ");
} else {
fragmentTag = customTagValue;
customFragmentTags = parsedTags.join(", ");
}
}
fragmentBody = parsed.body;
fragmentMode = isDraftFragment ? "create" : "view";
}
function appendDictationChunk(text: string) {
const cleaned = text.trim();
if (!cleaned) return;
const prefix =
fragmentBody.length > 0 &&
!fragmentBody.endsWith(" ") &&
!fragmentBody.endsWith("\n") &&
!fragmentBody.endsWith("\t")
? " "
: "";
fragmentBody = `${fragmentBody}${prefix}${cleaned} `;
}
async function startDictation() {
if (dictationBusy || dictationActive) return;
if (!isTauriRuntime()) {
dictationError = "Speech dictation is available in the desktop app only.";
return;
}
dictationBusy = true;
dictationError = "";
dictationStatus = "Checking microphone access...";
try {
await probeMicrophoneAccess();
dictationStatus = "Starting dictation...";
const started = await Promise.race([
startSpeechDictation(),
new Promise<never>((_, reject) =>
setTimeout(
() =>
reject(
new Error("Timed out waiting for speech process startup."),
),
8000,
),
),
]);
dictationActive = true;
if (started?.pid) {
dictationStatus = "Dictation started.";
}
} catch (error) {
dictationError = String(error);
dictationActive = false;
} finally {
dictationBusy = false;
}
}
async function stopDictation() {
if (dictationBusy || !dictationActive) return;
dictationBusy = true;
dictationError = "";
try {
await stopSpeechDictation();
} catch (error) {
dictationError = String(error);
} finally {
dictationActive = false;
dictationStatus = "Dictation stopped.";
dictationBusy = false;
}
}
async function toggleDictation() {
if (dictationActive) {
await stopDictation();
return;
}
await startDictation();
}
onMount(() => {
if (!isTauriRuntime()) return;
let disposed = false;
void (async () => {
const { listen } = await import("@tauri-apps/api/event");
const unlisten = await listen<{ text?: string }>(
"speech-transcript",
(event) => {
if (disposed || !dictationActive) return;
if (fragmentMode !== "edit" && fragmentMode !== "create") return;
const text = event.payload?.text ?? "";
appendDictationChunk(text);
},
);
const unlistenStatus = await listen<{ state?: string; message?: string }>(
"speech-status",
(event) => {
const state = event.payload?.state ?? "";
const message = event.payload?.message ?? "";
if (message) {
dictationStatus = message;
}
if (state === "listening") {
dictationError = "";
return;
}
if (state === "error") {
dictationError = message || "Speech process error.";
dictationActive = false;
return;
}
if (state === "stopped") {
dictationActive = false;
}
},
);
if (disposed) {
unlisten();
return;
}
unlistenTranscript = unlisten;
unlistenSpeechStatus = unlistenStatus;
})();
return () => {
disposed = true;
if (unlistenTranscript) {
unlistenTranscript();
unlistenTranscript = null;
}
if (unlistenSpeechStatus) {
unlistenSpeechStatus();
unlistenSpeechStatus = null;
}
};
});
onDestroy(() => {
if (dictationActive) {
void stopDictation();
}
});
$: fragmentTypeOptions = $settingsFragmentTypes.length
? $settingsFragmentTypes
: ["General"];
$: tagOptions = $settingsTags;
$: if (openDocumentId !== lastFragmentDocumentId) {
loadFragmentFormFromDocument();
lastFragmentDocumentId = openDocumentId;
}
$: if (
!fragmentType ||
(!fragmentTypeOptions.includes(fragmentType) &&
fragmentType !== customTypeValue)
) {
fragmentType = fragmentTypeOptions[0];
}
$: if (
!fragmentTag ||
(!tagOptions.includes(fragmentTag) && fragmentTag !== customTagValue)
) {
fragmentTag = tagOptions[0] ?? customTagValue;
}
$: if (!externalEditRequested) {
suppressExternalEditRequest = false;
}
$: if (
externalEditRequested &&
!suppressExternalEditRequest &&
fragmentMode === "view"
) {
fragmentMode = "edit";
}
$: if (fragmentMode === "view" && dictationActive) {
void stopDictation();
}
</script>
<section class="fragment-surface">
{#if dictationError || dictationStatus}
<div
class="dictation-indicator"
class:is-error={Boolean(dictationError)}
role="status"
aria-live="polite"
>
{dictationError || dictationStatus}
</div>
{/if}
{#if fragmentMode === "view"}
<article class="fragment-view">
{@html renderMarkdown(openDocumentContent)}
</article>
{:else}
<form
class="fragment-form"
on:submit|preventDefault={fragmentMode === "create"
? createNewFragment
: saveFragmentEdits}
>
<h2>{fragmentMode === "create" ? "New Fragment" : "Edit Fragment"}</h2>
<input
type="text"
placeholder="Title"
bind:value={fragmentTitle}
aria-label="Fragment title"
/>
<div class="fragment-form-row">
<select bind:value={fragmentType} aria-label="Fragment type">
{#each fragmentTypeOptions as type}
<option value={type}>{type}</option>
{/each}
<option value={customTypeValue}>Custom</option>
</select>
{#if fragmentType === customTypeValue}
<input
type="text"
placeholder="Custom type"
bind:value={customFragmentType}
aria-label="Custom fragment type"
/>
{:else}
<input
type="text"
value={fragmentType}
disabled
aria-label="Selected fragment type"
/>
{/if}
</div>
<div class="fragment-form-row">
<select bind:value={fragmentTag} aria-label="Primary fragment tag">
{#if tagOptions.length === 0}
<option value={customTagValue}>Custom</option>
{:else}
{#each tagOptions as tag}
<option value={tag}>{tag}</option>
{/each}
<option value={customTagValue}>Custom</option>
{/if}
</select>
<input
type="text"
placeholder={fragmentTag === customTagValue
? "Custom tags (comma separated)"
: "Additional tags (optional, comma separated)"}
bind:value={customFragmentTags}
aria-label="Custom fragment tags"
/>
</div>
<textarea
rows="5"
placeholder="Fragment text"
bind:value={fragmentBody}
aria-label="Fragment body"
></textarea>
<div class="fragment-actions">
<button
type="button"
class="fragment-secondary"
class:is-active={dictationActive}
on:click={() => void toggleDictation()}
disabled={dictationBusy || !isTauriRuntime()}
aria-label={dictationActive ? "Stop dictation" : "Start dictation"}
title={dictationActive ? "Stop dictation" : "Start dictation"}
>
{dictationActive ? "Stop Dictation" : "Start Dictation"}
</button>
<button type="submit" class="fragment-submit"
>{fragmentMode === "create"
? "Create Fragment"
: "Save Fragment"}</button
>
<button
type="button"
class="fragment-secondary"
on:click={cancelFragmentEdit}>Cancel</button
>
</div>
</form>
{/if}
</section>
<style>
.fragment-surface {
min-height: 0;
flex: 1;
overflow: auto;
padding: 0 14px 14px;
position: relative;
}
.dictation-indicator {
position: absolute;
top: 8px;
right: 22px;
z-index: 30;
border: 1px solid var(--border-soft);
border-radius: 8px;
background: color-mix(in srgb, var(--surface-1) 94%, var(--bg-editor) 6%);
color: var(--text-dim);
font-size: 0.76rem;
line-height: 1.35;
padding: 6px 9px;
max-width: min(56ch, 60%);
box-shadow: 0 8px 20px
color-mix(in srgb, var(--bg-app) 35%, transparent 65%);
pointer-events: none;
}
.dictation-indicator.is-error {
color: #fca5a5;
border-color: color-mix(in srgb, #ef4444 45%, var(--border-soft) 55%);
background: color-mix(in srgb, #2a1414 52%, var(--surface-1) 48%);
}
.fragment-form {
width: min(100%, 920px);
margin: 0 auto;
border: none;
border-radius: 0;
background: transparent;
padding: 28px 36px;
display: flex;
flex-direction: column;
gap: 12px;
}
.fragment-view {
width: min(100%, 920px);
margin: 0 auto;
border: none;
border-radius: 0;
background: transparent;
padding: 28px 36px;
display: flex;
flex-direction: column;
gap: 14px;
color: var(--text-primary);
font-size: 0.92rem;
line-height: 1.65;
font-family:
"Segoe UI Variable", "Segoe UI", "Segoe UI Emoji", "Apple Color Emoji",
"Noto Color Emoji", Inter, Roboto, Helvetica, Arial, sans-serif;
}
.fragment-view :global(h1),
.fragment-view :global(h2),
.fragment-view :global(h3),
.fragment-view :global(h4),
.fragment-view :global(h5),
.fragment-view :global(h6) {
margin: 0 0 8px;
}
.fragment-view :global(p),
.fragment-view :global(ul),
.fragment-view :global(ol),
.fragment-view :global(blockquote),
.fragment-view :global(pre) {
margin: 0 0 10px;
}
.fragment-view :global(code) {
background: var(--surface-2);
border: 1px solid var(--border-soft);
border-radius: 4px;
padding: 1px 4px;
font-family: Consolas, "Courier New", monospace;
font-size: 0.82rem;
}
.fragment-view :global(.markdown-tag-list) {
display: inline-flex;
flex-wrap: wrap;
gap: 6px;
vertical-align: middle;
}
.fragment-view :global(.markdown-tag-chip) {
display: inline-flex;
align-items: center;
border: 1px solid var(--border-soft);
border-radius: 999px;
padding: 1px 8px;
font-size: 0.74rem;
line-height: 1.35;
color: var(--text-muted);
background: color-mix(in srgb, var(--surface-2) 90%, var(--bg-editor) 10%);
}
.fragment-form h2 {
font-size: 1rem;
font-weight: 600;
color: var(--text-primary);
margin-bottom: 2px;
}
.fragment-form input,
.fragment-form select,
.fragment-form textarea {
width: 100%;
border: 1px solid var(--border-soft);
border-radius: 8px;
background-color: color-mix(
in srgb,
var(--surface-1) 88%,
var(--bg-editor) 12%
);
color: var(--text-primary);
padding: 10px 11px;
font-size: 0.88rem;
font-family:
"Segoe UI Variable", "Segoe UI", "Segoe UI Emoji", "Apple Color Emoji",
"Noto Color Emoji", Inter, Roboto, Helvetica, Arial, sans-serif;
}
.fragment-form textarea {
resize: vertical;
min-height: 220px;
line-height: 1.55;
}
.fragment-form-row {
display: grid;
grid-template-columns: 180px minmax(0, 1fr);
gap: 8px;
}
.fragment-submit {
width: fit-content;
border-radius: 8px;
border: 1px solid var(--border-strong);
background: color-mix(in srgb, var(--surface-2) 84%, var(--bg-hover) 16%);
color: var(--text-primary);
padding: 8px 12px;
font-size: 0.82rem;
cursor: pointer;
}
.fragment-submit:hover {
background: var(--bg-hover);
}
.fragment-actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.fragment-secondary {
border-radius: 8px;
border: 1px solid var(--border-soft);
background: color-mix(in srgb, var(--surface-1) 90%, var(--bg-editor) 10%);
color: var(--text-muted);
padding: 8px 12px;
font-size: 0.82rem;
cursor: pointer;
}
.fragment-secondary:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.fragment-secondary.is-active {
border-color: var(--border-strong);
color: var(--text-primary);
background: var(--bg-active);
}
@media (max-width: 980px) {
.fragment-surface {
padding: 4px 8px 10px;
}
.dictation-indicator {
right: 10px;
top: 6px;
max-width: calc(100% - 20px);
}
.fragment-form,
.fragment-view {
width: 100%;
padding: 18px 16px;
font-size: 0.89rem;
}
.fragment-form-row {
grid-template-columns: 1fr;
}
}
</style>

View File

@ -0,0 +1,303 @@
<!-- @format -->
<script lang="ts">
export let openDocumentId = "";
export let openDocumentName = "";
export let openDocumentContent = "";
export let onDocumentContentChange: (content: string) => void = () => {};
type SimpleListItem = {
id: number;
text: string;
};
let items: SimpleListItem[] = [];
let nextItemId = 1;
let lastDocumentId = "";
let newItemText = "";
let editingItemId: number | null = null;
let editingItemText = "";
function parseListItems(content: string): SimpleListItem[] {
const lines = (content ?? "").split(/\r?\n/);
const parsed: SimpleListItem[] = [];
for (const line of lines) {
const bullet = line.match(/^\s*(?:[-*+]|\d+\.)\s+(.+)$/);
if (bullet) {
parsed.push({ id: parsed.length + 1, text: bullet[1].trim() });
continue;
}
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
parsed.push({ id: parsed.length + 1, text: trimmed });
}
return parsed;
}
function serializeList(title: string, listItems: SimpleListItem[]): string {
const heading = (title ?? "").trim() || "Untitled List";
if (!listItems.length) {
return `# ${heading}\n\n`;
}
const body = listItems
.map((item) => item.text.trim())
.filter(Boolean)
.map((text) => `- ${text}`)
.join("\n");
return `# ${heading}\n\n${body}`;
}
function persist() {
onDocumentContentChange(serializeList(openDocumentName, items));
}
function resetForDocument() {
items = parseListItems(openDocumentContent);
nextItemId = (items[items.length - 1]?.id ?? 0) + 1;
newItemText = "";
editingItemId = null;
editingItemText = "";
}
function addItem() {
const text = newItemText.trim();
if (!text) return;
items = [{ id: nextItemId, text }, ...items];
nextItemId += 1;
newItemText = "";
persist();
}
function startEditItem(id: number) {
const existing = items.find((item) => item.id === id);
if (!existing) return;
editingItemId = id;
editingItemText = existing.text;
}
function saveEditItem() {
if (editingItemId === null) return;
const text = editingItemText.trim();
if (!text) return;
const id = editingItemId;
items = items.map((item) => (item.id === id ? { ...item, text } : item));
editingItemId = null;
editingItemText = "";
persist();
}
function cancelEditItem() {
editingItemId = null;
editingItemText = "";
}
function removeItem(id: number) {
if (editingItemId === id) {
cancelEditItem();
}
items = items.filter((item) => item.id !== id);
persist();
}
$: if (openDocumentId !== lastDocumentId) {
resetForDocument();
lastDocumentId = openDocumentId;
}
</script>
<section class="list-surface">
<div class="list-card">
<form class="list-create" on:submit|preventDefault={addItem}>
<input
type="text"
placeholder="Add a list item"
bind:value={newItemText}
aria-label="Add list item"
/>
<button type="submit" class="list-add-btn">Add</button>
</form>
<ul class="list-items">
{#each items as item}
<li class="list-item">
{#if editingItemId === item.id}
<input
type="text"
class="list-edit-input"
bind:value={editingItemText}
on:keydown={(event) => {
if (event.key === "Enter") saveEditItem();
if (event.key === "Escape") cancelEditItem();
}}
/>
<div class="list-actions">
<button
type="button"
class="list-btn save"
on:click={saveEditItem}>Save</button
>
<button
type="button"
class="list-btn ghost"
on:click={cancelEditItem}>Cancel</button
>
</div>
{:else}
<span class="list-text">{item.text}</span>
<div class="list-actions">
<button
type="button"
class="list-btn ghost"
on:click={() => startEditItem(item.id)}>Edit</button
>
<button
type="button"
class="list-btn danger"
on:click={() => removeItem(item.id)}>Remove</button
>
</div>
{/if}
</li>
{/each}
</ul>
</div>
</section>
<style>
.list-surface {
min-height: 0;
flex: 1;
overflow: auto;
padding: 0 14px 14px;
}
.list-card {
width: min(100%, 920px);
margin: 0 auto;
border: none;
border-radius: 0;
background: transparent;
padding: 28px 36px;
display: flex;
flex-direction: column;
gap: 12px;
max-height: 100%;
overflow: visible;
}
.list-create {
display: flex;
gap: 8px;
}
.list-create input,
.list-edit-input {
width: 100%;
border: 1px solid var(--border-soft);
border-radius: 8px;
background: color-mix(in srgb, var(--surface-1) 88%, var(--bg-editor) 12%);
color: var(--text-primary);
padding: 10px 11px;
font-size: 0.88rem;
}
.list-add-btn {
border-radius: 8px;
border: 1px solid var(--border-strong);
background: color-mix(in srgb, var(--surface-2) 84%, var(--bg-hover) 16%);
color: var(--text-primary);
padding: 9px 14px;
font-size: 0.82rem;
font-weight: 600;
cursor: pointer;
}
.list-add-btn:hover {
background: var(--bg-hover);
}
.list-items {
list-style: none;
display: flex;
flex-direction: column;
gap: 10px;
}
.list-item {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
border: 1px solid var(--border-soft);
border-radius: 8px;
padding: 10px 12px;
background: color-mix(in srgb, var(--surface-1) 90%, var(--bg-editor) 10%);
}
.list-text {
font-size: 0.9rem;
color: var(--text-primary);
line-height: 1.45;
word-break: break-word;
}
.list-actions {
display: flex;
gap: 6px;
}
.list-btn {
border-radius: 7px;
border: 1px solid var(--border-soft);
background: color-mix(in srgb, var(--surface-1) 90%, var(--bg-editor) 10%);
color: var(--text-muted);
padding: 6px 10px;
font-size: 0.78rem;
cursor: pointer;
}
.list-btn.save {
border-color: var(--border-strong);
background: color-mix(in srgb, var(--surface-2) 84%, var(--bg-hover) 16%);
color: var(--text-primary);
}
.list-btn.danger:hover,
.list-btn.ghost:hover,
.list-btn.save:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
@media (max-width: 980px) {
.list-surface {
padding: 4px 8px 10px;
}
.list-card {
width: 100%;
padding: 18px 16px;
}
.list-create {
flex-wrap: wrap;
}
.list-add-btn {
width: 100%;
}
.list-item {
grid-template-columns: minmax(0, 1fr);
row-gap: 8px;
}
.list-actions {
justify-content: flex-end;
}
}
</style>

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More