Compare commits
45 Commits
5bd9d72cc6
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| e8c8ddd48d | |||
|
|
d82738e7ea | ||
|
|
e005872ba0 | ||
|
|
d3e82a3ebb | ||
|
|
af8cbc1c96 | ||
|
|
ee6467a7ac | ||
|
|
cdf9a8bf18 | ||
|
|
f767bb5175 | ||
|
|
444aa37be2 | ||
|
|
15051cfa7a | ||
|
|
c5e78311e6 | ||
|
|
60b76c6d97 | ||
|
|
d12681b79f | ||
|
|
6c498c5f40 | ||
|
|
310370ef66 | ||
|
|
f4e6238176 | ||
|
|
d8cf7814ab | ||
|
|
50b69aadbf | ||
|
|
6cd121fa80 | ||
|
|
28a5d65f1a | ||
|
|
b4e97e14f3 | ||
|
|
78b4df1028 | ||
|
|
96101e4310 | ||
|
|
9c07d3195f | ||
|
|
4b2162505c | ||
|
|
8f1ba08e54 | ||
|
|
a16e1cc42a | ||
|
|
e19582201f | ||
|
|
f09afd2d9e | ||
|
|
f4eb278692 | ||
|
|
3ec501388c | ||
|
|
50b7fa784c | ||
|
|
5445bb0eec | ||
|
|
77b94e2b27 | ||
|
|
2cb2f0e4e8 | ||
|
|
e70982c8b6 | ||
|
|
7a1aec0d9f | ||
|
|
5eb19e022e | ||
|
|
00a43e0fbc | ||
|
|
c1aa6829c9 | ||
|
|
98acf6220e | ||
|
|
2308158976 | ||
|
|
7860ca6ad1 | ||
|
|
40ac075633 | ||
|
|
c75788503f |
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"playwright": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"@playwright/mcp@latest"
|
||||
],
|
||||
"env": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
136
.claude/CLAUDE.md
Normal file
136
.claude/CLAUDE.md
Normal file
@@ -0,0 +1,136 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# Development
|
||||
source ~/.nvm/nvm.sh && npm start # Start Electron app with hot-reload
|
||||
|
||||
# Build & Package
|
||||
source ~/.nvm/nvm.sh && npm run make # Build distributable packages
|
||||
source ~/.nvm/nvm.sh && npm run package # Package without making installers
|
||||
|
||||
# Lint
|
||||
source ~/.nvm/nvm.sh && npm run lint # ESLint over .ts/.tsx files
|
||||
|
||||
# Database migrations (Drizzle)
|
||||
source ~/.nvm/nvm.sh && npx drizzle-kit generate # Generate migration from schema changes
|
||||
source ~/.nvm/nvm.sh && npx drizzle-kit push # Push schema directly (dev only)
|
||||
```
|
||||
|
||||
There is no test suite currently.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
Adiuva is a local-first Electron desktop app. The three Electron processes communicate via a custom tRPC↔IPC bridge (the public `electron-trpc` package is incompatible with tRPC v11, so a custom implementation is used).
|
||||
|
||||
### Process Boundaries
|
||||
|
||||
```
|
||||
Renderer (React) ──ipcLink──► Preload (contextBridge) ──IPC──► Main (tRPC router + SQLite)
|
||||
```
|
||||
|
||||
1. **Main process** (`src/main/`) — Node.js, owns the database and all business logic
|
||||
- `index.ts` — Window creation, app lifecycle
|
||||
- `ipc.ts` — Custom handler that bridges `ipcMain` to tRPC procedures
|
||||
- `router/index.ts` — All tRPC routers (clients, projects, tasks, checkpoints, notes, settings, ai)
|
||||
- `db/index.ts` — Drizzle + better-sqlite3, WAL mode, singleton `getDb()`
|
||||
- `db/schema.ts` — All table definitions (clients, projects, tasks, checkpoints, notes)
|
||||
- `store.ts` — electron-store for persistent UI settings (e.g., `sidebarCollapsed`)
|
||||
|
||||
2. **Preload** (`src/preload/trpc.ts`) — Exposes `window.electronTRPC` with `sendMessage()` / `onMessage()`
|
||||
|
||||
3. **Renderer** (`src/renderer/`) — React 19, never accesses Node APIs directly
|
||||
- `lib/ipcLink.ts` — Custom TRPCLink that routes calls through `window.electronTRPC`
|
||||
- `lib/trpc.ts` — `createTRPCReact<AppRouter>()` typed client
|
||||
- `index.tsx` — QueryClient + tRPC + Router providers
|
||||
- All data access is through `trpc.*.*useQuery()` / `trpc.*.*.useMutation()`
|
||||
|
||||
### Routing
|
||||
|
||||
File-based routing via TanStack Router. Add a file to `src/renderer/routes/` and the route tree (`src/renderer/routeTree.gen.ts`) is auto-regenerated by the Vite plugin on next `npm start`. Routes:
|
||||
- `__root.tsx` — Root layout wrapping everything in `AppShell`
|
||||
- `index.tsx`, `tasks.tsx`, `timeline.tsx`, `projects.tsx`
|
||||
|
||||
### Database
|
||||
|
||||
Schema lives in `src/main/db/schema.ts`. Migrations are in `src/main/db/migrations/`. The DB is created in Electron's `userData` directory as `adiuva.db`. On startup, `initDb()` runs non-destructive migrations (CREATE TABLE IF NOT EXISTS).
|
||||
|
||||
To add a new table or column: edit `schema.ts`, run `drizzle-kit generate`, then `drizzle-kit push` (dev) or commit the migration file.
|
||||
|
||||
### Adding a New Feature (end-to-end pattern)
|
||||
|
||||
1. **Schema** — Add table/columns to `src/main/db/schema.ts`
|
||||
2. **Router** — Add a tRPC sub-router in `src/main/router/index.ts`, merge it into `appRouter`
|
||||
3. **Types** — `AppRouter` is exported from `src/main/router/index.ts` and imported in `src/renderer/lib/trpc.ts` — types flow automatically
|
||||
4. **UI** — Create components under `src/renderer/components/<feature>/`, use `trpc.*.*useQuery()` for data
|
||||
|
||||
### AI Subsystem (`src/main/ai/`)
|
||||
|
||||
LangGraph-based agentic system with pluggable LLM providers (OpenAI, Anthropic, GitHub Copilot).
|
||||
|
||||
**Orchestrator** (`orchestrator.ts`): Classifies user intent → routes to one of three specialist agents:
|
||||
- **Project agent** — project-scoped Q&A with tools: `read_project_notes`, `add_task`, `get_summary`, `suggest_checkpoints`, `suggest_tasks`
|
||||
- **Knowledge agent** — cross-project semantic search via `vector_search_all`
|
||||
- **General agent** — workspace-wide `add_task`
|
||||
|
||||
Tool-calling strategy differs by provider: OpenAI/Anthropic use LangChain `bindTools()` + ToolMessage loop (max 5 iterations); Copilot uses SDK-native tools (loop handled internally).
|
||||
|
||||
**Streaming**: Orchestrator calls `sendStreamChunk(sender, token, done)` over IPC channel `'ai:stream'`. Renderer subscribes via `window.electronAI.onStreamChunk()` in `AIChatPanel.tsx`. `<tool_call>` blocks are filtered before sending to renderer.
|
||||
|
||||
**Provider factory** (`llm.ts`): `gpt-4o-mini` (OpenAI), `claude-sonnet-4-20250514` (Anthropic), or ChatCopilot wrapper — all with `temperature: 0.3` and streaming enabled.
|
||||
|
||||
**Token storage** (`token.ts`) — two-tier fallback:
|
||||
1. electron-store + `safeStorage` — encrypted at rest (preferred)
|
||||
2. Plain electron-store — last resort (e.g. WSL with no keyring)
|
||||
|
||||
**AI approval pattern**: Tasks and checkpoints have `isAiSuggested` (bool) and `isApproved` (bool) columns. AI-suggested items appear in the UI pending user approval before being treated as real records.
|
||||
|
||||
### Vector Embeddings (`src/main/db/vectordb.ts`)
|
||||
|
||||
LanceDB stored in `{userData}/vectors/`. Table schema: `{ id, projectId, content, vector }`. Vectors are 1536-dimensional (`text-embedding-3-small`). Embeddings use a priority chain: Copilot CLI token → OpenAI token.
|
||||
|
||||
- Note create/update fires `upsertNoteEmbedding()` (fire-and-forget, errors swallowed)
|
||||
- `migrateNotesIfNeeded()` backfills existing notes on first startup
|
||||
- `searchNotes(query, limit=5)` is called by the Knowledge agent tool
|
||||
|
||||
### Key Config Notes
|
||||
|
||||
- Vite configs use `.mts` extension (not `.ts`) to avoid ESM/CJS conflicts with electron-forge's externalize-deps plugin
|
||||
- `@/*` path alias resolves to `src/renderer/*` (TypeScript + Vite + shadcn/ui all share this alias)
|
||||
- shadcn/ui style: **new-york**, base color: **neutral**
|
||||
- Icons: **lucide-react** throughout — do not introduce other icon libraries
|
||||
- Tailwind 4 (not 3) — use CSS variable theming via `globals.css`, not `tailwind.config.js`
|
||||
- Notes use Milkdown (`@milkdown/crepe`) as the markdown editor (`src/renderer/components/notes/MilkdownEditor.tsx`)
|
||||
- Routes: `index`, `tasks`, `timeline`, `projects`, `notes.$noteId` (note ID is a URL param)
|
||||
|
||||
## Design Context
|
||||
|
||||
### Users
|
||||
Freelancers and solo professionals managing their own client work — projects, tasks, notes, and timelines. They work alone and need a single workspace that keeps everything organized without the overhead of enterprise tools. The AI assistant is a force multiplier, helping them stay on top of their workload.
|
||||
|
||||
### Brand Personality
|
||||
**Calm, intelligent, warm.** Adiuva is a thoughtful companion, not a flashy tool. It should feel like a well-organized desk — everything in its place, nothing competing for attention. The tone is confident and understated, never loud or gamified.
|
||||
|
||||
### Aesthetic Direction
|
||||
- **Visual tone**: Editorial, premium, content-first. Inspired by Notion's clean typography and warm neutrals, but with a distinct identity through the warm pinkish-white canvas and golden yellow accent
|
||||
- **Light mode**: Soft and warm — pinkish-white (`#f4edf3`) canvas, golden yellow (`#fbc881`) primary, slate blue-gray (`#8a8ea9`) secondary, dusty lavender borders (`#c8c3cd`)
|
||||
- **Dark mode**: Stark monochrome — near-black canvas (`#0c0c0c`), crisp white text, dark gray surfaces (`#323232`). No color accent; primary is pure white
|
||||
- **Typography**: Geist (geometric sans-serif) at 400/500/600. Tight tracking on large headings (`-1px`). Body at `text-sm`, metadata at `text-xs`
|
||||
- **Corners**: 10px base radius, consistently rounded. Chat elements use `rounded-2xl`
|
||||
- **Signature effects**: Glassmorphism on AI inputs/floating chat (`backdrop-blur-xl`, transparency). Spring physics animations (stiffness 400, damping 30). Subtle scale-and-fade transitions
|
||||
- **Anti-references**: No gamification (badges, streaks, confetti). No corporate/enterprise density. Keep it mature and professional
|
||||
|
||||
### Design Principles
|
||||
|
||||
1. **Clarity over cleverness** — Every element should communicate its purpose instantly. Prefer clear hierarchy and whitespace over decorative flourish. Information density should feel comfortable, not cramped.
|
||||
|
||||
2. **AI as quiet partner** — The AI is deeply integrated (floating chat, suggestions) but never intrusive. AI-suggested items use dashed borders to signal "pending." The Sparkles icon is the consistent AI identity marker.
|
||||
|
||||
3. **Warmth in restraint** — The palette is deliberately warm (pinkish whites, golden yellows) to feel approachable without being playful. Dark mode trades warmth for focus. Let the content breathe.
|
||||
|
||||
4. **Motion with purpose** — Spring physics and glassmorphism create a sense of physicality and depth. Animations should feel natural and responsive, never decorative or slow. Every transition should reinforce spatial relationships.
|
||||
|
||||
5. **Confidence through consistency** — Use the established token system (CSS variables, shadcn/ui primitives, Geist font). The user should feel in control — predictable patterns, keyboard-first interactions, no surprises.
|
||||
124
.gitea/workflows/build.yaml
Normal file
124
.gitea/workflows/build.yaml
Normal file
@@ -0,0 +1,124 @@
|
||||
name: Release Electron App
|
||||
run-name: Releasing ${{ gitea.ref_name }}
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
release-desktop:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: electronuserland/builder:wine
|
||||
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install System Dependencies for Linux Makers
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y fakeroot dpkg mono-complete
|
||||
|
||||
- name: Install Dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Set version from tag
|
||||
run: npm version "${GITHUB_REF_NAME#v}" --no-git-tag-version --allow-same-version
|
||||
|
||||
- name: Make App (Linux)
|
||||
run: npm run make -- --platform=linux --arch=x64
|
||||
|
||||
- name: Initialize Wine
|
||||
run: |
|
||||
export WINEDEBUG=-all
|
||||
export DISPLAY=
|
||||
wineboot --init
|
||||
env:
|
||||
WINEDEBUG: '-all'
|
||||
|
||||
- name: Make App (Windows)
|
||||
run: npm run make -- --platform=win32 --arch=x64
|
||||
env:
|
||||
WINEDEBUG: '-all'
|
||||
|
||||
- name: Create Gitea Release
|
||||
run: |
|
||||
GITEA_URL="http://10.0.0.119:3000"
|
||||
TAG="${GITHUB_REF_NAME}"
|
||||
REPO="${GITHUB_REPOSITORY}"
|
||||
TOKEN="${{ gitea.token }}"
|
||||
|
||||
# Check if release exists, create if not
|
||||
RELEASE_ID=$(curl -sf \
|
||||
-H "Authorization: token ${TOKEN}" \
|
||||
"${GITEA_URL}/api/v1/repos/${REPO}/releases/tags/${TAG}" \
|
||||
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
|
||||
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
RELEASE_ID=$(curl -sf \
|
||||
-X POST \
|
||||
-H "Authorization: token ${TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"${TAG}\",\"name\":\"${TAG}\"}" \
|
||||
"${GITEA_URL}/api/v1/repos/${REPO}/releases" \
|
||||
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
|
||||
fi
|
||||
|
||||
echo "Release ID: ${RELEASE_ID}"
|
||||
echo "RELEASE_ID=${RELEASE_ID}" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Upload Release Assets
|
||||
shell: bash
|
||||
run: |
|
||||
GITEA_URL="http://10.0.0.119:3000"
|
||||
REPO="${GITHUB_REPOSITORY}"
|
||||
TOKEN="${{ gitea.token }}"
|
||||
MAX_RETRIES=3
|
||||
|
||||
upload_file() {
|
||||
local file="$1"
|
||||
local name
|
||||
name=$(basename "$file")
|
||||
local encoded_name
|
||||
encoded_name=$(printf '%s' "$name" | sed 's/ /%20/g')
|
||||
local attempt=1
|
||||
|
||||
while [ $attempt -le $MAX_RETRIES ]; do
|
||||
local filesize
|
||||
filesize=$(stat -c%s "$file" 2>/dev/null || stat -f%z "$file" 2>/dev/null || echo "unknown")
|
||||
echo "Uploading ${name} (${filesize} bytes, attempt ${attempt}/${MAX_RETRIES})..."
|
||||
RESPONSE=$(curl -s -w "\n%{http_code}" \
|
||||
--max-time 300 \
|
||||
-X POST \
|
||||
-H "Authorization: token ${TOKEN}" \
|
||||
-H "Expect:" \
|
||||
-F "attachment=@${file}" \
|
||||
"${GITEA_URL}/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets?name=${encoded_name}")
|
||||
HTTP_CODE=$(echo "$RESPONSE" | tail -1)
|
||||
BODY=$(echo "$RESPONSE" | head -n -1)
|
||||
|
||||
if [ "$HTTP_CODE" -ge 200 ] 2>/dev/null && [ "$HTTP_CODE" -lt 300 ] 2>/dev/null; then
|
||||
echo "✅ Uploaded ${name}"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "⚠️ Upload failed (HTTP ${HTTP_CODE}), body: ${BODY}"
|
||||
echo "Retrying in 5s..."
|
||||
sleep 5
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
|
||||
echo "❌ Failed to upload ${name} after ${MAX_RETRIES} attempts"
|
||||
return 1
|
||||
}
|
||||
|
||||
FAILED=0
|
||||
while IFS= read -r -d '' file; do
|
||||
upload_file "$file" || FAILED=1
|
||||
done < <(find out/make -type f \( -name "*.exe" -o -name "*.zip" -o -name "*.deb" -o -name "*.rpm" \) -print0)
|
||||
|
||||
if [ $FAILED -eq 1 ]; then
|
||||
echo "Some uploads failed"
|
||||
exit 1
|
||||
fi
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -90,3 +90,7 @@ typings/
|
||||
|
||||
# Electron-Forge
|
||||
out/
|
||||
|
||||
# local config files
|
||||
.vscode/
|
||||
|
||||
|
||||
11
.vscode/mcp.json
vendored
11
.vscode/mcp.json
vendored
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"servers": {
|
||||
"shadcn": {
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"shadcn@latest",
|
||||
"mcp"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
1230
docs/floating-ai-integration-guide.md
Normal file
1230
docs/floating-ai-integration-guide.md
Normal file
File diff suppressed because it is too large
Load Diff
222
forge.config.ts
222
forge.config.ts
@@ -7,12 +7,232 @@ import { AutoUnpackNativesPlugin } from '@electron-forge/plugin-auto-unpack-nati
|
||||
import { VitePlugin } from '@electron-forge/plugin-vite';
|
||||
import { FusesPlugin } from '@electron-forge/plugin-fuses';
|
||||
import { FuseV1Options, FuseVersion } from '@electron/fuses';
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import { execSync } from 'node:child_process';
|
||||
|
||||
// Packages externalized in vite.main.config.mts that must be installed at runtime.
|
||||
// Keep this list in sync with the Vite external array.
|
||||
const externalPackages = [
|
||||
'better-sqlite3',
|
||||
'@github/copilot-sdk',
|
||||
'@langchain/core',
|
||||
'@langchain/langgraph',
|
||||
'@langchain/openai',
|
||||
'@langchain/anthropic',
|
||||
'vectordb',
|
||||
'electron-squirrel-startup',
|
||||
'electron-store',
|
||||
];
|
||||
|
||||
const config: ForgeConfig = {
|
||||
packagerConfig: {
|
||||
asar: true,
|
||||
asar: {
|
||||
unpack: '**/{*.node,*.dll,*.so,*.dylib}',
|
||||
},
|
||||
name: 'adiuva',
|
||||
},
|
||||
rebuildConfig: {},
|
||||
hooks: {
|
||||
packageAfterCopy: async (_forgeConfig, buildPath, _electronVersion, platform, arch) => {
|
||||
// The VitePlugin's ignore filter only copies .vite/ into the build.
|
||||
// Externalized packages need to be installed into node_modules here.
|
||||
// At this point, only .vite/ exists. The VitePlugin writes package.json
|
||||
// in its own afterCopy hook (which may run after ours). Read from source.
|
||||
const srcPjPath = path.resolve(__dirname, 'package.json');
|
||||
const pjPath = path.resolve(buildPath, 'package.json');
|
||||
const pj = JSON.parse(fs.readFileSync(srcPjPath, 'utf-8'));
|
||||
|
||||
// Keep only externalized packages in dependencies
|
||||
const filtered: Record<string, string> = {};
|
||||
for (const pkg of externalPackages) {
|
||||
if (pj.dependencies?.[pkg]) {
|
||||
filtered[pkg] = pj.dependencies[pkg];
|
||||
}
|
||||
}
|
||||
pj.dependencies = filtered;
|
||||
delete pj.devDependencies;
|
||||
fs.writeFileSync(pjPath, JSON.stringify(pj, null, 2));
|
||||
|
||||
// Copy lockfile for reproducible installs
|
||||
const lockSrc = path.resolve(buildPath, '..', '..', 'package-lock.json');
|
||||
if (fs.existsSync(lockSrc)) {
|
||||
fs.copyFileSync(lockSrc, path.resolve(buildPath, 'package-lock.json'));
|
||||
}
|
||||
|
||||
// Install only the externalized runtime deps
|
||||
console.log('[forge] Installing externalized dependencies...');
|
||||
execSync('npm install --omit=dev', {
|
||||
cwd: buildPath,
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, npm_config_nodedir: '' },
|
||||
});
|
||||
|
||||
const targetKey = `${platform}-${arch}`;
|
||||
|
||||
// vectordb uses platform-specific optional deps (@lancedb/vectordb-<platform>-<arch>-*).
|
||||
// npm install on Linux only pulls the Linux variant. Force-install the target's.
|
||||
const platformNativePackages: Record<string, Record<string, string>> = {
|
||||
'win32-x64': {
|
||||
'@lancedb/vectordb-win32-x64-msvc': '',
|
||||
},
|
||||
'linux-x64': {
|
||||
'@lancedb/vectordb-linux-x64-gnu': '',
|
||||
},
|
||||
'darwin-x64': {
|
||||
'@lancedb/vectordb-darwin-x64': '',
|
||||
},
|
||||
'darwin-arm64': {
|
||||
'@lancedb/vectordb-darwin-arm64': '',
|
||||
},
|
||||
};
|
||||
const nativePkgs = platformNativePackages[targetKey];
|
||||
if (nativePkgs) {
|
||||
// Remove wrong-platform lancedb native packages
|
||||
const nmPath = path.join(buildPath, 'node_modules', '@lancedb');
|
||||
if (fs.existsSync(nmPath)) {
|
||||
for (const entry of fs.readdirSync(nmPath)) {
|
||||
if (entry.startsWith('vectordb-') && !Object.keys(nativePkgs).includes(`@lancedb/${entry}`)) {
|
||||
fs.rmSync(path.join(nmPath, entry), { recursive: true, force: true });
|
||||
console.log(`[forge] Removed non-target native package: @lancedb/${entry}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Install correct platform packages
|
||||
const pkgsToInstall = Object.keys(nativePkgs).join(' ');
|
||||
console.log(`[forge] Installing platform-specific packages for ${targetKey}: ${pkgsToInstall}`);
|
||||
execSync(`npm install ${pkgsToInstall} --omit=dev --no-save --force`, {
|
||||
cwd: buildPath,
|
||||
stdio: 'inherit',
|
||||
});
|
||||
}
|
||||
|
||||
// Remove cross-platform prebuilt binaries that don't match the target.
|
||||
// Packages like @github/copilot ship prebuilds for all platforms;
|
||||
// keeping foreign-arch .node files breaks rpmbuild's strip step.
|
||||
const nodeModulesPath = path.join(buildPath, 'node_modules');
|
||||
const findPrebuilds = (dir: string): string[] => {
|
||||
const results: string[] = [];
|
||||
if (!fs.existsSync(dir)) return results;
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (entry.name === 'prebuilds') {
|
||||
results.push(full);
|
||||
} else {
|
||||
results.push(...findPrebuilds(full));
|
||||
}
|
||||
}
|
||||
}
|
||||
return results;
|
||||
};
|
||||
|
||||
for (const prebuildsDir of findPrebuilds(nodeModulesPath)) {
|
||||
for (const entry of fs.readdirSync(prebuildsDir)) {
|
||||
if (entry !== targetKey) {
|
||||
const fullPath = path.join(prebuildsDir, entry);
|
||||
fs.rmSync(fullPath, { recursive: true, force: true });
|
||||
console.log(`[forge] Removed non-target prebuild: ${entry}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// @github/copilot ships @teddyzhu/clipboard-* platform packages outside
|
||||
// of prebuilds/. Remove non-target variants to avoid bundling wrong binaries.
|
||||
const clipboardDir = path.join(buildPath, 'node_modules', '@github', 'copilot', 'clipboard', 'node_modules', '@teddyzhu');
|
||||
if (fs.existsSync(clipboardDir)) {
|
||||
const targetClipboardMap: Record<string, string> = {
|
||||
'win32-x64': 'clipboard-win32-x64-msvc',
|
||||
'win32-arm64': 'clipboard-win32-arm64-msvc',
|
||||
'linux-x64': 'clipboard-linux-x64-gnu',
|
||||
'linux-arm64': 'clipboard-linux-arm64-gnu',
|
||||
'darwin-x64': 'clipboard-darwin-x64',
|
||||
'darwin-arm64': 'clipboard-darwin-arm64',
|
||||
};
|
||||
const wantedPkg = targetClipboardMap[targetKey];
|
||||
for (const entry of fs.readdirSync(clipboardDir)) {
|
||||
if (entry.startsWith('clipboard-') && entry !== wantedPkg) {
|
||||
fs.rmSync(path.join(clipboardDir, entry), { recursive: true, force: true });
|
||||
console.log(`[forge] Removed non-target clipboard package: @teddyzhu/${entry}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// ── Post-rebuild: fix native binaries for cross-compilation ──────
|
||||
// Forge runs @electron/rebuild AFTER packageAfterCopy, which
|
||||
// recompiles native addons for the BUILD platform (Linux).
|
||||
// packageAfterPrune runs AFTER rebuild+prune, so we can safely
|
||||
// replace the Linux .node files with the correct target prebuilts.
|
||||
packageAfterPrune: async (_forgeConfig, buildPath, _electronVersion, platform, arch) => {
|
||||
const targetKey = `${platform}-${arch}`;
|
||||
const buildKey = `${process.platform}-${process.arch}`;
|
||||
if (targetKey === buildKey) return; // native build — nothing to fix
|
||||
|
||||
console.log(`[forge:afterPrune] Cross-compile fixup: ${buildKey} → ${targetKey}`);
|
||||
const electronVersion = JSON.parse(
|
||||
fs.readFileSync(path.resolve(__dirname, 'node_modules', 'electron', 'package.json'), 'utf-8'),
|
||||
).version;
|
||||
|
||||
// Replace native addons that @electron/rebuild compiled for the host.
|
||||
const nativeModules = ['better-sqlite3'];
|
||||
for (const mod of nativeModules) {
|
||||
const modDir = path.join(buildPath, 'node_modules', mod);
|
||||
if (!fs.existsSync(modDir)) continue;
|
||||
|
||||
// Remove the host-platform binary left by @electron/rebuild
|
||||
const buildRelease = path.join(modDir, 'build', 'Release');
|
||||
if (fs.existsSync(buildRelease)) {
|
||||
fs.rmSync(buildRelease, { recursive: true, force: true });
|
||||
console.log(`[forge:afterPrune] Cleaned host-platform build/Release for ${mod}`);
|
||||
}
|
||||
|
||||
// Download the correct prebuilt for the TARGET platform
|
||||
console.log(`[forge:afterPrune] Downloading ${mod} prebuilt for ${targetKey} (Electron ${electronVersion})...`);
|
||||
execSync(
|
||||
`npx --yes prebuild-install -r electron -t ${electronVersion} ` +
|
||||
`--platform ${platform} --arch ${arch} --tag-prefix v --verbose`,
|
||||
{ cwd: modDir, stdio: 'inherit' },
|
||||
);
|
||||
|
||||
// Verify the binary exists and is for the correct platform.
|
||||
const releaseDir = path.join(modDir, 'build', 'Release');
|
||||
if (!fs.existsSync(releaseDir)) {
|
||||
throw new Error(
|
||||
`[forge] FATAL: build/Release/ not found for ${mod} after prebuild-install. ` +
|
||||
`The native binary was not downloaded.`,
|
||||
);
|
||||
}
|
||||
const nodeFiles = fs.readdirSync(releaseDir).filter((f) => f.endsWith('.node'));
|
||||
if (nodeFiles.length === 0) {
|
||||
throw new Error(
|
||||
`[forge] FATAL: No .node files in build/Release/ for ${mod} after prebuild-install.`,
|
||||
);
|
||||
}
|
||||
for (const f of nodeFiles) {
|
||||
const buf = Buffer.alloc(4);
|
||||
const fd = fs.openSync(path.join(releaseDir, f), 'r');
|
||||
fs.readSync(fd, buf, 0, 4, 0);
|
||||
fs.closeSync(fd);
|
||||
// ELF magic: 0x7f 'E' 'L' 'F'
|
||||
if (buf[0] === 0x7f && buf[1] === 0x45 && buf[2] === 0x4c && buf[3] === 0x46) {
|
||||
throw new Error(
|
||||
`[forge] FATAL: ${mod} build/Release/${f} is an ELF binary! ` +
|
||||
`Cross-compilation failed — refusing to package a Linux .node for Windows.`,
|
||||
);
|
||||
}
|
||||
// PE magic: 'M' 'Z' (0x4d 0x5a) — expected for win32
|
||||
if (platform === 'win32' && !(buf[0] === 0x4d && buf[1] === 0x5a)) {
|
||||
throw new Error(
|
||||
`[forge] FATAL: ${mod} build/Release/${f} is not a PE (Windows) binary! ` +
|
||||
`Magic bytes: ${buf.toString('hex')}. Refusing to package.`,
|
||||
);
|
||||
}
|
||||
console.log(`[forge:afterPrune] Verified ${mod}/${f} — correct platform ✓`);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
makers: [
|
||||
new MakerSquirrel({}),
|
||||
new MakerZIP({}, ['darwin']),
|
||||
|
||||
22
knip.json
Normal file
22
knip.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"$schema": "https://unpkg.com/knip@5/schema.json",
|
||||
"tags": ["-lintignore"],
|
||||
"entry": [
|
||||
"src/main/index.ts",
|
||||
"src/preload/index.ts",
|
||||
"src/preload/trpc.ts",
|
||||
"forge.config.ts",
|
||||
"vite.main.config.mts",
|
||||
"vite.preload.config.mts",
|
||||
"vite.renderer.config.mts"
|
||||
],
|
||||
"ignoreDependencies": [
|
||||
"postcss",
|
||||
"@electron-forge/shared-types",
|
||||
"@milkdown/plugin-upload",
|
||||
"@milkdown/prose"
|
||||
],
|
||||
"ignore": [
|
||||
"src/renderer/components/ui/**"
|
||||
]
|
||||
}
|
||||
4642
package-lock.json
generated
4642
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
18
package.json
18
package.json
@@ -10,10 +10,11 @@
|
||||
"package": "electron-forge package",
|
||||
"make": "electron-forge make",
|
||||
"publish": "electron-forge publish",
|
||||
"lint": "eslint --ext .ts,.tsx ."
|
||||
"lint": "eslint --ext .ts,.tsx .",
|
||||
"knip": "knip"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "rmusso",
|
||||
"author": "roberto",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@electron-forge/cli": "^7.11.1",
|
||||
@@ -28,6 +29,7 @@
|
||||
"@tanstack/router-vite-plugin": "^1.161.1",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/electron-squirrel-startup": "^1.0.2",
|
||||
"@types/node": "^25.3.3",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@typescript-eslint/eslint-plugin": "^5.62.0",
|
||||
@@ -38,6 +40,7 @@
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-import-resolver-typescript": "^4.4.4",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"knip": "^5.85.0",
|
||||
"postcss": "^8.5.6",
|
||||
"shadcn": "^3.8.5",
|
||||
"tailwindcss": "^4.2.0",
|
||||
@@ -46,6 +49,14 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/geist": "^5.2.8",
|
||||
"@github/copilot-sdk": "^0.1.25",
|
||||
"@hello-pangea/dnd": "^18.0.1",
|
||||
"@langchain/anthropic": "^1.3.19",
|
||||
"@langchain/core": "^1.1.27",
|
||||
"@langchain/langgraph": "^1.1.5",
|
||||
"@langchain/openai": "^1.2.9",
|
||||
"@milkdown/crepe": "^7.18.0",
|
||||
"@tailwindcss/typography": "^0.5.19",
|
||||
"@tailwindcss/vite": "^4.2.0",
|
||||
"@tanstack/react-query": "^5.90.21",
|
||||
"@tanstack/react-router": "^1.161.1",
|
||||
@@ -65,8 +76,11 @@
|
||||
"react": "^19.2.4",
|
||||
"react-day-picker": "^9.13.2",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"vectordb": "^0.21.2",
|
||||
"zod": "^4.3.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
# Ralph Agent Instructions
|
||||
|
||||
You are an autonomous coding agent working on a software project.
|
||||
|
||||
## Your Task
|
||||
|
||||
1. Read the full app PRD at `prd-main.md` (in the same directory as this file)
|
||||
2. Read the PRD at `prd.json` (in the same directory as this file)
|
||||
3. Read the progress log at `progress.txt` (check Codebase Patterns section first)
|
||||
4. Check you're on the correct branch from PRD `branchName`. If not, check it out or create from main.
|
||||
5. Pick the **highest priority** user story where `passes: false`
|
||||
6. Implement that single user story
|
||||
7. Run quality checks (e.g., typecheck, lint, test - use whatever your project requires)
|
||||
8. Update CLAUDE.md files if you discover reusable patterns (see below)
|
||||
9. If checks pass, commit ALL changes with message: `feat: [Story ID] - [Story Title]`
|
||||
10. Update the PRD to set `passes: true` for the completed story
|
||||
11. Append your progress to `progress.txt`
|
||||
|
||||
## Progress Report Format
|
||||
|
||||
APPEND to progress.txt (never replace, always append):
|
||||
```
|
||||
## [Date/Time] - [Story ID]
|
||||
- What was implemented
|
||||
- Files changed
|
||||
- **Learnings for future iterations:**
|
||||
- Patterns discovered (e.g., "this codebase uses X for Y")
|
||||
- Gotchas encountered (e.g., "don't forget to update Z when changing W")
|
||||
- Useful context (e.g., "the evaluation panel is in component X")
|
||||
---
|
||||
```
|
||||
|
||||
The learnings section is critical - it helps future iterations avoid repeating mistakes and understand the codebase better.
|
||||
|
||||
## Consolidate Patterns
|
||||
|
||||
If you discover a **reusable pattern** that future iterations should know, add it to the `## Codebase Patterns` section at the TOP of progress.txt (create it if it doesn't exist). This section should consolidate the most important learnings:
|
||||
|
||||
```
|
||||
## Codebase Patterns
|
||||
- Example: Use `sql<number>` template for aggregations
|
||||
- Example: Always use `IF NOT EXISTS` for migrations
|
||||
- Example: Export types from actions.ts for UI components
|
||||
```
|
||||
|
||||
Only add patterns that are **general and reusable**, not story-specific details.
|
||||
|
||||
## Update CLAUDE.md Files
|
||||
|
||||
Before committing, check if any edited files have learnings worth preserving in nearby CLAUDE.md files:
|
||||
|
||||
1. **Identify directories with edited files** - Look at which directories you modified
|
||||
2. **Check for existing CLAUDE.md** - Look for CLAUDE.md in those directories or parent directories
|
||||
3. **Add valuable learnings** - If you discovered something future developers/agents should know:
|
||||
- API patterns or conventions specific to that module
|
||||
- Gotchas or non-obvious requirements
|
||||
- Dependencies between files
|
||||
- Testing approaches for that area
|
||||
- Configuration or environment requirements
|
||||
|
||||
**Examples of good CLAUDE.md additions:**
|
||||
- "When modifying X, also update Y to keep them in sync"
|
||||
- "This module uses pattern Z for all API calls"
|
||||
- "Tests require the dev server running on PORT 3000"
|
||||
- "Field names must match the template exactly"
|
||||
|
||||
**Do NOT add:**
|
||||
- Story-specific implementation details
|
||||
- Temporary debugging notes
|
||||
- Information already in progress.txt
|
||||
|
||||
Only update CLAUDE.md if you have **genuinely reusable knowledge** that would help future work in that directory.
|
||||
|
||||
## Quality Requirements
|
||||
|
||||
- ALL commits must pass your project's quality checks (typecheck, lint, test)
|
||||
- Do NOT commit broken code
|
||||
- Keep changes focused and minimal
|
||||
- Follow existing code patterns
|
||||
|
||||
## Browser Testing (If Available)
|
||||
|
||||
For any story that changes UI, verify it works in the browser if you have browser testing tools configured (e.g., via MCP):
|
||||
|
||||
1. Navigate to the relevant page
|
||||
2. Verify the UI changes work as expected
|
||||
3. Take a screenshot if helpful for the progress log
|
||||
|
||||
If no browser tools are available, note in your progress report that manual browser verification is needed.
|
||||
|
||||
## Stop Condition
|
||||
|
||||
After completing a user story, check if ALL stories have `passes: true`.
|
||||
|
||||
If ALL stories are complete and passing, reply with:
|
||||
<promise>COMPLETE</promise>
|
||||
|
||||
If there are still stories with `passes: false`, end your response normally (another iteration will pick up the next story).
|
||||
|
||||
## Important
|
||||
|
||||
- Work on ONE story per iteration
|
||||
- Commit frequently
|
||||
- Keep CI green
|
||||
- Read the Codebase Patterns section in progress.txt before starting
|
||||
@@ -1,487 +0,0 @@
|
||||
# PRD: Adiuva — MVP Implementation
|
||||
|
||||
> **Status:** APPROVED / READY FOR DEV
|
||||
> **Version:** 1.0 (MVP)
|
||||
> **Date:** 2026-02-19
|
||||
> **Stack:** Electron · React · TypeScript · shadcn/ui · Tailwind · Drizzle ORM · SQLite · LanceDB · GitHub Copilot SDK
|
||||
> **Figma:** [Full File](https://www.figma.com/design/FxyJG9kpou4DfD7jM9WHKP/Desk)
|
||||
|
||||
---
|
||||
|
||||
## Introduction
|
||||
|
||||
Adiuva is a local-first desktop workspace acting as a "Digital Executive Secretary." It centralizes notes, tasks, and project context into a local SQLite database and exposes a multi-agent AI layer (via GitHub Copilot SDK) that proactively surfaces insights and drafts actions. Data never leaves the machine, making it safe for enterprise environments.
|
||||
|
||||
---
|
||||
|
||||
## Goals
|
||||
|
||||
- Ship a working Electron desktop app with five sections: Home, Timeline, Tasks, Projects, Notes.
|
||||
- All data persisted locally in SQLite (zero cloud dependency for data storage).
|
||||
- Hierarchical Client → Sub-Client → Project structure fully navigable from a sidebar tree.
|
||||
- "Fluid Curtain" pull-down gesture that transitions any view into a full-screen AI chat scoped to the current context.
|
||||
- Multi-agent AI system (@Orchestrator, @ProjectAgent, @EmailAgent, @KnowledgeAgent) integrated via GitHub Copilot SDK.
|
||||
- Milestone completion = every section functional at the level described in User Stories below.
|
||||
|
||||
---
|
||||
|
||||
## UI Summary (from Figma)
|
||||
|
||||
### Shared Shell
|
||||
- **Left sidebar:** 240px, `#fafafa` background, border-right `#e5e5e5`.
|
||||
- Top: Adiuva logo/wordmark.
|
||||
- Nav items: Home (house icon), Timeline (chart-gantt icon), Tasks (clipboard-check icon), Projects (folder-kanban icon). Active item gets `#f5f5f5` accent + no extra border.
|
||||
- Bottom: Collapse button (panel-left icon).
|
||||
- **Right edge:** Vertical rotated label "keep scrolling for AI / next section" + chevron-down. This is the visual affordance for the Fluid Curtain pull-down gesture.
|
||||
- **Font:** Geist (Regular 400, Medium 500, Semibold 600). Sizes: sm=14px, base=16px.
|
||||
- **Colors:** bg=`#ffffff`, foreground=`#0a0a0a`, muted=`#737373`, border=`#e5e5e5`, sidebar=`#fafafa`, sidebar-accent=`#f5f5f5`, primary=`#171717`, primary-fg=`#fafafa`.
|
||||
|
||||
### HOME
|
||||
- Top-right corner: stat chip showing "N Task due" count.
|
||||
- Main area (centered, max-w ~1088px): AI greeting `✦ Hello, {name}` (Heading 2, Geist Semibold 30px, -1px tracking).
|
||||
- Below: AI-generated daily brief paragraph with **bold** key phrases inline.
|
||||
- Chat input box: white, border `#d4d4d4`, shadow-lg, 109px tall, placeholder "Ask me anythings...", Send button (black, icon + label) bottom-right of the box.
|
||||
- Below chat: 4 suggestion chips (`Item` component) — icon badge + short prompt text — in a 4-column flex row.
|
||||
|
||||
### TIMELINE
|
||||
- Main content area: placeholder background `#fef2f2` (the Gantt chart is not yet designed in Figma; implementation is free to choose a library).
|
||||
- Same sidebar + right-edge Fluid Curtain affordance.
|
||||
|
||||
### TASKS
|
||||
- Header row: 4 stat cards — "Total task", "To Do", "In Progress", "Completed" — each with an icon and count.
|
||||
- Below: search bar (full-width, placeholder "Search tasks or projects...") + "Order by" dropdown (right) + status filter tabs (All | To Do | In Progress | Completed).
|
||||
- Task list rows (flat, full-width):
|
||||
- Checkbox (left)
|
||||
- Title (bold, 14px) + description subtitle (gray, 14px)
|
||||
- Priority chip: `HIGH` (up-arrow, red-toned) | `MEDIUM` (right-arrow, gray) | `LOW` (down-arrow, green-toned)
|
||||
- Due date chip (calendar icon + "Due Mon DD")
|
||||
- Breadcrumb path (Client > Sub-Client > Project, chevron-separated)
|
||||
- Assignee (person icon + name string)
|
||||
- Completed tasks show row with green-tinted background.
|
||||
|
||||
### PROJECTS
|
||||
- **Left panel (tree):** "Projects" heading + `+` new button + search input. Hierarchical tree: Client (folder, bold) → Sub-Client (folder) → Project (circle/file). Expand/collapse chevrons. Active project highlighted.
|
||||
- **Right panel (project detail):**
|
||||
- Breadcrumb (Client > Sub-Client) at top.
|
||||
- Project name as H1.
|
||||
- 3 stat cards: Notes count | Tasks Complete (x/y fraction) | Checkpoints (x/y fraction).
|
||||
- AI Project Summary card (sparkle icon + generated paragraph).
|
||||
- **Project Timeline:** inline Gantt — months across top (Feb 2026, Mar 2026 …), horizontal bar with dot markers for each checkpoint. Legend: To Do (dark) / Completed (green). "+ Add" button top-right.
|
||||
- **Tasks (Kanban):** 3 columns — To Do / In progress / Completed. Task cards: title, description, priority chip, due date, assignee. "+ Add" per column header.
|
||||
- **Notes list:** flat list of note entries + "+ Add" button.
|
||||
|
||||
### NOTES
|
||||
- Milkdown editor (standalone route) for writing/editing a single note.
|
||||
- Markdown-native, full-screen editor style.
|
||||
|
||||
---
|
||||
|
||||
## Data Schema
|
||||
|
||||
```typescript
|
||||
// clients — hierarchical (self-referencing parentId)
|
||||
export const clients = sqliteTable('clients', {
|
||||
id: text('id').primaryKey(), // UUID
|
||||
parentId: text('parent_id'), // null = top-level client
|
||||
name: text('name').notNull(),
|
||||
industry: text('industry'),
|
||||
createdAt: integer('created_at').notNull(),
|
||||
});
|
||||
|
||||
// projects — attached to a client/sub-client, or orphan
|
||||
export const projects = sqliteTable('projects', {
|
||||
id: text('id').primaryKey(),
|
||||
clientId: text('client_id').references(() => clients.id), // nullable
|
||||
name: text('name').notNull(),
|
||||
status: text('status').default('active'), // active | archived
|
||||
aiSummary: text('ai_summary'), // AI-generated paragraph
|
||||
createdAt: integer('created_at').notNull(),
|
||||
});
|
||||
|
||||
// tasks — belong to a project (or global/orphan if projectId null)
|
||||
export const tasks = sqliteTable('tasks', {
|
||||
id: text('id').primaryKey(),
|
||||
projectId: text('project_id').references(() => projects.id), // nullable
|
||||
title: text('title').notNull(),
|
||||
description: text('description'),
|
||||
status: text('status').default('todo'), // todo | in_progress | done
|
||||
priority: text('priority').default('medium'), // high | medium | low
|
||||
assignee: text('assignee'), // plain string name
|
||||
dueDate: integer('due_date'), // unix timestamp
|
||||
createdAt: integer('created_at').notNull(),
|
||||
});
|
||||
|
||||
// checkpoints — milestones on the per-project timeline
|
||||
export const checkpoints = sqliteTable('checkpoints', {
|
||||
id: text('id').primaryKey(),
|
||||
projectId: text('project_id').references(() => projects.id).notNull(),
|
||||
title: text('title').notNull(),
|
||||
date: integer('date').notNull(), // unix timestamp
|
||||
isAiSuggested: integer('is_ai_suggested').default(0), // 0=manual, 1=AI
|
||||
isApproved: integer('is_approved').default(1), // 0=pending AI approval
|
||||
createdAt: integer('created_at').notNull(),
|
||||
});
|
||||
|
||||
// notes — markdown content attached to a project
|
||||
export const notes = sqliteTable('notes', {
|
||||
id: text('id').primaryKey(),
|
||||
projectId: text('project_id').references(() => projects.id), // nullable
|
||||
title: text('title').notNull(),
|
||||
content: text('content').notNull(), // raw Markdown
|
||||
createdAt: integer('created_at').notNull(),
|
||||
updatedAt: integer('updated_at').notNull(),
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## User Stories
|
||||
|
||||
### PHASE 1 — Foundation
|
||||
|
||||
---
|
||||
|
||||
#### US-001: Electron + React scaffold
|
||||
**Description:** As a developer, I need a working Electron app with React+TypeScript and a shared main/renderer process setup so that all other features have a platform to run on.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] `electron-builder` or `electron-vite` scaffold with hot-reload in dev.
|
||||
- [ ] Main process can open a `BrowserWindow` serving the React app.
|
||||
- [ ] TypeScript strict mode enabled, `tsconfig.json` configured.
|
||||
- [ ] `package.json` scripts: `dev`, `build`, `preview`.
|
||||
- [ ] App opens without errors on Linux, macOS, Windows.
|
||||
|
||||
---
|
||||
|
||||
#### US-002: SQLite database + Drizzle ORM setup
|
||||
**Description:** As a developer, I need the SQLite database initialized with Drizzle ORM so that all CRUD operations use a typed, schema-driven interface.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] `better-sqlite3` (or `@electric-sql/pglite` alternative) installed in main process.
|
||||
- [ ] Drizzle schema file defines all 5 tables (clients, projects, tasks, checkpoints, notes).
|
||||
- [ ] Migration runs on app start; DB file created at `~/.adiuva/data.db` (or `app.getPath('userData')`).
|
||||
- [ ] Drizzle Studio accessible in dev mode (`drizzle-kit studio`).
|
||||
- [ ] TypeScript types inferred from schema (no manual type duplication).
|
||||
|
||||
---
|
||||
|
||||
#### US-003: App shell — sidebar navigation
|
||||
**Description:** As a user, I want a persistent left sidebar so that I can navigate between all sections of the app.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Sidebar renders at 240px with `#fafafa` background and right border.
|
||||
- [ ] Nav items: Home (house), Timeline (chart-gantt), Tasks (clipboard-check), Projects (folder-kanban). Each uses Lucide icon + label.
|
||||
- [ ] Active route highlights item with `#f5f5f5` accent background.
|
||||
- [ ] Collapse button at bottom toggles sidebar to icon-only mode (64px).
|
||||
- [ ] Router renders correct view for each nav item (React Router or TanStack Router).
|
||||
- [ ] Verify in browser using dev-browser skill.
|
||||
|
||||
---
|
||||
|
||||
#### US-004: Client CRUD (hierarchical)
|
||||
**Description:** As a user, I want to create, rename, and delete Clients and Sub-Clients so that I can mirror real-world corporate structures.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] "New Client" action creates a top-level client (parentId = null).
|
||||
- [ ] "New Sub-Client" action (available on a selected client) creates a child (parentId = selected client's id).
|
||||
- [ ] Client and Sub-Client names are editable via inline rename or modal.
|
||||
- [ ] Deleting a client warns if it has child clients or projects; cascade delete is opt-in.
|
||||
- [ ] Changes are immediately persisted to SQLite.
|
||||
- [ ] TypeScript types pass; no `any`.
|
||||
|
||||
---
|
||||
|
||||
#### US-005: Project CRUD
|
||||
**Description:** As a user, I want to create projects attached to a client/sub-client or as standalone orphans so that I can track both client and internal work.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] "New Project" dialog asks for name and optionally a client (dropdown, searchable).
|
||||
- [ ] Projects with no client appear under an "Internal / No Client" group in the tree.
|
||||
- [ ] Project can be re-parented (moved to a different client) via edit dialog.
|
||||
- [ ] Project status toggled between `active` and `archived`.
|
||||
- [ ] Archived projects hidden by default; toggle to show.
|
||||
- [ ] Persisted to SQLite immediately.
|
||||
|
||||
---
|
||||
|
||||
#### US-006: Projects sidebar tree view
|
||||
**Description:** As a user, I want to see all clients, sub-clients, and projects in a collapsible tree in the Projects section so that I can navigate the hierarchy at a glance.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Tree renders: Client (folder icon) → Sub-Client (folder icon) → Project (circle icon).
|
||||
- [ ] Clients and sub-clients expand/collapse independently.
|
||||
- [ ] Search input filters tree in real-time (client name, sub-client name, project name).
|
||||
- [ ] Clicking a project loads the Project Detail panel on the right.
|
||||
- [ ] Active project is highlighted in the tree.
|
||||
- [ ] Verify in browser using dev-browser skill.
|
||||
|
||||
---
|
||||
|
||||
#### US-007: Task CRUD (global Tasks view)
|
||||
**Description:** As a user, I want a global task list where I can create, filter, search, and update tasks so that I can manage all work across projects in one place.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] 4 stat cards at top: Total, To Do, In Progress, Completed — update reactively.
|
||||
- [ ] Search filters tasks by title or description, case-insensitive.
|
||||
- [ ] Status filter tabs (All | To Do | In Progress | Completed) filter list.
|
||||
- [ ] "Order by" dropdown supports: Due Date, Priority, Created Date.
|
||||
- [ ] Task rows show: checkbox, title, description, priority chip (HIGH/MEDIUM/LOW with color), due date chip, breadcrumb (Client > Sub-Client > Project), assignee.
|
||||
- [ ] Clicking checkbox toggles status: todo → done (skip in_progress for quick-complete).
|
||||
- [ ] Inline "New Task" button opens a creation modal with fields: title, description, priority, due date, project (optional), assignee (optional).
|
||||
- [ ] All changes persisted to SQLite.
|
||||
- [ ] Verify in browser using dev-browser skill.
|
||||
|
||||
---
|
||||
|
||||
#### US-008: Manual Timeline (global & per-project)
|
||||
**Description:** As a user, I want to view and manually create timeline checkpoints on a Gantt-style view so that I have full control over milestone dates.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Timeline view renders a horizontal time axis (months) with dot markers for each checkpoint.
|
||||
- [ ] Global Timeline shows checkpoints from all projects (color-coded by project or status).
|
||||
- [ ] Per-project timeline (in Project Detail) scoped to that project's checkpoints only.
|
||||
- [ ] "+ Add" button opens a dialog: title, date picker, project (in global view).
|
||||
- [ ] Checkpoint dots distinguish status: To Do (dark/filled) vs Completed (green).
|
||||
- [ ] "Today" marker line displayed on the timeline.
|
||||
- [ ] Clicking a checkpoint dot shows a popover with title, date, and delete action.
|
||||
- [ ] Persisted to SQLite.
|
||||
- [ ] Verify in browser using dev-browser skill.
|
||||
|
||||
---
|
||||
|
||||
#### US-009: Project Detail view
|
||||
**Description:** As a user, I want a rich project detail panel that shows notes count, tasks summary, AI summary, timeline, Kanban, and notes list in one scrollable view.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Breadcrumb (Client > Sub-Client) rendered at top.
|
||||
- [ ] Stat cards: Notes count | Tasks Complete (x/y) | Checkpoints (x/y).
|
||||
- [ ] AI Project Summary card shows sparkle icon + placeholder text ("AI summary will appear here") until agent generates it.
|
||||
- [ ] Inline Project Timeline (same Gantt component as US-008, scoped).
|
||||
- [ ] Kanban board: To Do / In Progress / Completed columns. Task cards show title, description, priority, due date, assignee. Drag between columns updates `status`.
|
||||
- [ ] Notes list: title + creation date for each note. Click opens Milkdown editor. "+ Add" creates new note.
|
||||
- [ ] Verify in browser using dev-browser skill.
|
||||
|
||||
---
|
||||
|
||||
#### US-010: Notes editor (Milkdown)
|
||||
**Description:** As a user, I want a full-screen Markdown editor for each note so that I can write rich content without leaving the app.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Milkdown editor renders in a dedicated route (`/notes/:noteId`).
|
||||
- [ ] Supports: headings, bold, italic, code blocks, bullet lists, ordered lists, blockquotes.
|
||||
- [ ] Auto-saves content to SQLite on change (debounced, 500ms).
|
||||
- [ ] Back navigation returns to the project detail view (or previous location).
|
||||
- [ ] Note title editable at the top (separate from Milkdown content).
|
||||
- [ ] Verify in browser using dev-browser skill.
|
||||
|
||||
---
|
||||
|
||||
### PHASE 2 — The Fluid Curtain & Agents
|
||||
|
||||
---
|
||||
|
||||
#### US-011: Fluid Curtain — pull-down gesture + animation
|
||||
**Description:** As a user, I want to pull down from the top of any view to slide the app off-screen and reveal the AI chat layer beneath.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Scrolling up past the top of content (overscroll) OR pressing a keyboard shortcut (e.g., `Cmd/Ctrl+K` or `⌥↓`) triggers the curtain.
|
||||
- [ ] App panel slides down using Framer Motion spring animation, exiting the bottom of the viewport.
|
||||
- [ ] AI Chat view is fully revealed below (full-screen, no sidebar obstruction).
|
||||
- [ ] Pulling the app back up (swipe/scroll from bottom or shortcut) re-covers the chat.
|
||||
- [ ] Animation is smooth (no jank). Spring config: stiffness 300, damping 30.
|
||||
- [ ] Right-edge "keep scrolling for AI" label and chevron are visible in every section as the affordance.
|
||||
- [ ] Verify in browser using dev-browser skill.
|
||||
|
||||
---
|
||||
|
||||
#### US-012: Context-scoped AI chat
|
||||
**Description:** As a user, I want the AI chat (revealed by the curtain) to know the context I was in so that answers are scoped to the right project or global scope.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] When curtain is pulled from a Project Detail view, a context header displays "Chatting about: [Project Name]".
|
||||
- [ ] When pulled from Home, context is global (all data).
|
||||
- [ ] Context is passed as a system message to the GitHub Copilot SDK call (project notes, tasks, checkpoints as structured JSON).
|
||||
- [ ] Agent responses reference only documents within the scoped project.
|
||||
- [ ] Chat history is session-only (not persisted in MVP).
|
||||
|
||||
---
|
||||
|
||||
#### US-013: GitHub Copilot SDK integration + @Orchestrator
|
||||
**Description:** As a developer, I need the GitHub Copilot SDK wired up with an Orchestrator agent that routes user messages to the correct specialist agent.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] SDK initialized in main process with enterprise credentials (from env/config).
|
||||
- [ ] `@Orchestrator` reads user intent and calls `route_to_project`, `route_to_general`, or `route_to_email` tool.
|
||||
- [ ] Routing result invokes the correct specialist agent and returns its response.
|
||||
- [ ] Streaming responses supported (tokens shown incrementally in chat UI).
|
||||
- [ ] Errors handled gracefully (SDK timeout, auth failure) with user-facing message.
|
||||
|
||||
---
|
||||
|
||||
#### US-014: @ProjectAgent with project tools
|
||||
**Description:** As a user, I want the AI to answer project-specific questions and take actions (add task, suggest checkpoints) within the scoped project.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] `read_project_notes` tool fetches all notes for the project from SQLite.
|
||||
- [ ] `add_task` tool creates a task in the project (writes to SQLite) and confirms in chat.
|
||||
- [ ] `suggest_checkpoints` tool returns a list of proposed checkpoints (title + date) as interactive cards in chat (Approve / Reject each).
|
||||
- [ ] Approved checkpoints are inserted into `checkpoints` table with `is_ai_suggested=1, is_approved=1`.
|
||||
- [ ] `get_summary` tool generates a 2-3 sentence project summary and updates `projects.ai_summary` in SQLite.
|
||||
|
||||
---
|
||||
|
||||
### PHASE 3 — Intelligence & RAG
|
||||
|
||||
---
|
||||
|
||||
#### US-015: LanceDB vector store setup + note embedding
|
||||
**Description:** As a developer, I need notes and project content embedded into LanceDB so that semantic search is possible across all projects.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] LanceDB initialized in main process, storing vectors at `~/.adiuva/vectors/`.
|
||||
- [ ] On note save (create or update), content is embedded via GitHub Copilot SDK embeddings endpoint and stored in LanceDB with `{noteId, projectId, content}` metadata.
|
||||
- [ ] Existing notes are indexed on first startup (migration script).
|
||||
- [ ] Embedding errors logged but do not block the save operation.
|
||||
|
||||
---
|
||||
|
||||
#### US-016: @KnowledgeAgent — semantic search across all projects
|
||||
**Description:** As a user, I want to ask "what did we decide about X?" and get answers pulled from across all past project notes, not just the current one.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] `vector_search_all` tool accepts a query string, returns top-5 semantically similar note chunks from LanceDB.
|
||||
- [ ] Results include source note title and project name for attribution.
|
||||
- [ ] @Orchestrator routes knowledge queries to @KnowledgeAgent.
|
||||
- [ ] Response in chat includes inline citations ("From: Project A — Meeting Notes, Feb 12").
|
||||
|
||||
---
|
||||
|
||||
#### US-017: AI checkpoint suggestions from notes
|
||||
**Description:** As a user, I want the AI to proactively analyze my meeting notes and suggest timeline checkpoints I may have missed.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Triggered manually ("Suggest checkpoints" button in Project Detail timeline header) or by @ProjectAgent tool call.
|
||||
- [ ] @ProjectAgent reads all notes for the project, extracts date-anchored commitments, returns as suggested checkpoints.
|
||||
- [ ] Suggestions appear as dismissible cards in the Timeline UI with `isAiSuggested=1, isApproved=0`.
|
||||
- [ ] Approve → `isApproved` set to 1, checkpoint appears on timeline.
|
||||
- [ ] Reject → checkpoint deleted.
|
||||
- [ ] Verify in browser using dev-browser skill.
|
||||
|
||||
---
|
||||
|
||||
#### US-018: Home dashboard — AI daily brief
|
||||
**Description:** As a user, I want the Home screen to greet me with an AI-generated daily brief summarizing my tasks and suggesting actions.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] On app open, @Orchestrator queries tasks due today/this week and recent project activity.
|
||||
- [ ] AI generates a personalized paragraph with key highlights (tasks due, suggested calls/emails).
|
||||
- [ ] Brief is displayed below the greeting with **bold** key phrases inline (as in Figma).
|
||||
- [ ] 4 suggestion chips below the chat box are pre-populated with context-relevant queries.
|
||||
- [ ] Chat box on Home is scoped globally (no project context).
|
||||
- [ ] Verify in browser using dev-browser skill.
|
||||
|
||||
---
|
||||
|
||||
## Functional Requirements
|
||||
|
||||
- **FR-01:** All data stored locally in SQLite at `app.getPath('userData')/adiuva.db`.
|
||||
- **FR-02:** App functions fully offline; AI features degrade gracefully when network is unavailable.
|
||||
- **FR-03:** Client tree supports unlimited nesting depth but UI only needs to display 3 levels (Client → Sub-Client → Project).
|
||||
- **FR-04:** Tasks table has a nullable `projectId`; global Tasks view shows all tasks regardless.
|
||||
- **FR-05:** The "Fluid Curtain" animation must not lose the underlying view state (app slides but remains mounted).
|
||||
- **FR-06:** GitHub Copilot SDK credentials are stored in OS keychain (not plaintext config).
|
||||
- **FR-07:** Milkdown auto-save uses a 500ms debounce; unsaved indicator shown if pending.
|
||||
- **FR-08:** All IDs are UUIDs (use `crypto.randomUUID()`).
|
||||
- **FR-09:** Drizzle migrations run automatically on startup; never destructive.
|
||||
- **FR-10:** Kanban drag-and-drop updates `tasks.status` and `tasks.updatedAt` immediately in SQLite.
|
||||
|
||||
---
|
||||
|
||||
## Non-Goals (Out of Scope for MVP)
|
||||
|
||||
- Email client / inbox integration (EmailAgent tools are stubs only).
|
||||
- Cloud sync or multi-device support.
|
||||
- Real assignee accounts (assignee is a plain name string, not a user entity).
|
||||
- Notifications or system tray alerts.
|
||||
- Dark mode.
|
||||
- Mobile or web version.
|
||||
- Export to PDF/CSV.
|
||||
- Notes version history.
|
||||
|
||||
---
|
||||
|
||||
## Design Considerations
|
||||
|
||||
- **Font:** Geist via `@fontsource/geist` or CDN. Apply globally via CSS variable.
|
||||
- **Icons:** Lucide React (house, chart-gantt, clipboard-check, folder-kanban, panel-left, send, sparkles, chevron-down).
|
||||
- **Gantt:** ✅ Custom SVG component. Month labels on X axis, `<circle>` dots for checkpoints, `<line>` baseline, `<TodayMarker>`. Use `ResizeObserver` for responsive width.
|
||||
- **Kanban:** ✅ `@hello-pangea/dnd` — `<DragDropContext>` wrapping 3 `<Droppable>` columns, each task a `<Draggable>`.
|
||||
- **Fluid Curtain:** ✅ `framer-motion` `useMotionValue` + `useSpring`. Trigger: `wheel` event at `scrollTop === 0 && deltaY < 0` OR `Cmd/Ctrl+K`. Right-edge "keep scrolling for AI" label is a **visual hint only** (not interactive).
|
||||
- **shadcn/ui components to reuse:** Button, Input, Badge, Card, Dialog, Separator, Tabs, Tooltip, DropdownMenu, Popover.
|
||||
|
||||
---
|
||||
|
||||
## Technical Considerations
|
||||
|
||||
- **IPC:** ✅ `electron-trpc`. Define a single `appRouter` in main process exposing all domains (`tasks`, `projects`, `clients`, `checkpoints`, `notes`, `ai`). Renderer uses `trpc.[domain].[procedure].useQuery/useMutation()`. Zod validates all inputs at the boundary.
|
||||
- GitHub Copilot SDK may require enterprise SSO token; provide a settings screen for token input (US not in MVP scope, but infrastructure must exist).
|
||||
- LanceDB Node.js binding (`vectordb` package) runs in main process only.
|
||||
- Milkdown v7+ with React adapter. Plugin list: `commonmark`, `history`, `clipboard`, `math` (optional).
|
||||
- Use `electron-store` or `conf` for lightweight app settings (user name for greeting, sidebar collapsed state, etc.).
|
||||
|
||||
---
|
||||
|
||||
## Success Metrics
|
||||
|
||||
- All 5 sections navigable and functional with real SQLite-persisted data.
|
||||
- Fluid Curtain animation runs at 60fps with no layout shift on return.
|
||||
- @ProjectAgent correctly scopes a context query (zero responses sourcing from another project).
|
||||
- Note embedding + LanceDB retrieval returns relevant results for a simple semantic query.
|
||||
- App cold-start < 3 seconds on a modern machine.
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. ~~**Gantt library vs. custom SVG?**~~ ✅ Resolved: custom SVG component.
|
||||
2. ~~**GitHub Copilot SDK auth flow:**~~ ✅ Resolved: `keytar` (OS keychain). A minimal "Settings" screen for token input writes to keychain on save.
|
||||
3. ~~**IPC architecture:**~~ ✅ Resolved: `electron-trpc` with Zod validation. All DB/AI operations exposed as tRPC procedures in main process; renderer uses typed React Query hooks.
|
||||
4. **Milkdown vs. simpler editor:** Milkdown is powerful but has a learning curve. Is a simpler `CodeMirror`-based Markdown editor acceptable for MVP?
|
||||
5. **"Fluid Curtain" on Linux:** Overscroll behavior differs across OS/window managers. What's the fallback trigger (keyboard shortcut only)?
|
||||
|
||||
---
|
||||
|
||||
## Implementation Roadmap
|
||||
|
||||
### Phase 1 — Foundation (US-001 → US-010)
|
||||
|
||||
| Step | Story | Key Decision Point |
|
||||
|------|-------|-------------------|
|
||||
| 1.1 | US-001: Electron+React scaffold | ✅ **electron-forge + Vite plugin** (`npm init electron-app@latest -- --template=vite-typescript`) |
|
||||
| 1.2 | US-002: SQLite + Drizzle setup | Schema finalized; migrations strategy |
|
||||
| 1.3 | US-003: App shell + sidebar | ✅ **TanStack Router** (fully type-safe, `$projectId` params typed) |
|
||||
| 1.4 | US-004 + US-005: Client & Project CRUD | Data model confirmed |
|
||||
| 1.5 | US-006: Projects tree view | ✅ **Radix Collapsible + recursive `TreeNode`** (no extra dep, matches Figma) |
|
||||
| 1.6 | US-007: Tasks global view | |
|
||||
| 1.7 | US-008: Manual Timeline / Gantt | ✅ **Custom SVG component** (dot-on-axis, zero deps, matches Figma exactly) |
|
||||
| 1.8 | US-009: Project Detail view | ✅ **@hello-pangea/dnd** for Kanban drag-and-drop |
|
||||
| 1.9 | US-010: Milkdown editor | Plugin scope for MVP |
|
||||
|
||||
### Phase 2 — The Curtain & Agents (US-011 → US-014)
|
||||
|
||||
| Step | Story | Key Decision Point |
|
||||
|------|-------|-------------------|
|
||||
| 2.1 | US-011: Fluid Curtain animation | ✅ Wheel overscroll-up at `scrollTop=0` + `Cmd/Ctrl+K` shortcut. Right-edge label is visual-only (not a button). Framer Motion spring (`y` to viewport height). |
|
||||
| 2.2 | US-012: Context-scoped chat UI | Chat bubble components, streaming UI |
|
||||
| 2.3 | US-013: Copilot SDK + @Orchestrator | ✅ **`keytar`** for OS keychain token storage (main process only, IPC to renderer). |
|
||||
| 2.4 | US-014: @ProjectAgent tools | Tool schema definition + SQLite write-back |
|
||||
|
||||
### Phase 3 — Intelligence & RAG (US-015 → US-018)
|
||||
|
||||
| Step | Story | Key Decision Point |
|
||||
|------|-------|-------------------|
|
||||
| 3.1 | US-015: LanceDB setup + embedding | ✅ **GitHub Copilot SDK embeddings** (`text-embedding-3-small`). Chunk notes by paragraph (~500 tokens). |
|
||||
| 3.2 | US-016: @KnowledgeAgent search | Vector search tuning, k=5 default |
|
||||
| 3.3 | US-017: AI checkpoint suggestions | Prompt engineering for date extraction |
|
||||
| 3.4 | US-018: Home daily brief | Orchestrator routing for daily summary |
|
||||
|
||||
@@ -1,461 +0,0 @@
|
||||
{
|
||||
"project": "Adiuva",
|
||||
"branchName": "ralph/adiuva-mvp",
|
||||
"description": "Adiuva MVP — Local-first desktop workspace with hierarchical project management, Fluid Curtain AI chat overlay, and multi-agent intelligence via GitHub Copilot SDK",
|
||||
"userStories": [
|
||||
{
|
||||
"id": "US-001",
|
||||
"title": "Electron + React scaffold",
|
||||
"description": "As a developer, I need a working Electron app with React+TypeScript and a shared main/renderer process setup so that all other features have a platform to run on.",
|
||||
"acceptanceCriteria": [
|
||||
"electron-forge + Vite plugin scaffold with hot-reload in dev",
|
||||
"Main process opens a BrowserWindow serving the React app",
|
||||
"TypeScript strict mode enabled, tsconfig.json configured",
|
||||
"package.json scripts: dev, build, preview",
|
||||
"App opens without errors",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 1,
|
||||
"passes": true,
|
||||
"notes": "Completed in initial scaffold commit (f6cc8bb)"
|
||||
},
|
||||
{
|
||||
"id": "US-002",
|
||||
"title": "SQLite + Drizzle ORM schema and migrations",
|
||||
"description": "As a developer, I need the SQLite database initialized with Drizzle ORM so that all CRUD operations use a typed, schema-driven interface.",
|
||||
"acceptanceCriteria": [
|
||||
"better-sqlite3 and drizzle-orm installed as main-process dependencies",
|
||||
"Drizzle schema file defines all 5 tables matching the PRD exactly: clients (id, parentId, name, industry, createdAt), projects (id, clientId, name, status, aiSummary, createdAt), tasks (id, projectId, title, description, status, priority, assignee, dueDate, createdAt), checkpoints (id, projectId, title, date, isAiSuggested, isApproved, createdAt), notes (id, projectId, title, content, createdAt, updatedAt)",
|
||||
"DB file created at app.getPath('userData')/adiuva.db on startup",
|
||||
"Migration runs automatically on app start (drizzle-kit migrate or push); never destructive",
|
||||
"All IDs are UUIDs generated via crypto.randomUUID()",
|
||||
"TypeScript types inferred from schema with no manual type duplication",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 2,
|
||||
"passes": true,
|
||||
"notes": "Completed: better-sqlite3 + drizzle-orm, 5-table schema, non-destructive push migration via CREATE TABLE IF NOT EXISTS, WAL mode enabled"
|
||||
},
|
||||
{
|
||||
"id": "US-003",
|
||||
"title": "electron-trpc IPC bridge and appRouter scaffold",
|
||||
"description": "As a developer, I need electron-trpc wired up between main and renderer processes so that all DB and AI operations are exposed as type-safe tRPC procedures callable from the renderer.",
|
||||
"acceptanceCriteria": [
|
||||
"electron-trpc installed; IPC bridge configured in main process and preload script",
|
||||
"appRouter defined in main process with stub routers for all domains: clients, projects, tasks, checkpoints, notes, ai",
|
||||
"Renderer-side trpc client created with the correct IPC link and wrapped in TRPCProvider + QueryClientProvider",
|
||||
"A health.ping procedure returns 'pong' and is successfully callable from the renderer (verified via console log or React component)",
|
||||
"Zod imported and used to validate at least one procedure input",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 3,
|
||||
"passes": true,
|
||||
"notes": "Completed: electron-trpc IPC bridge, appRouter with stub routers for all 7 domains (health, clients, projects, tasks, checkpoints, notes, ai), renderer TRPCProvider+QueryClientProvider, health.ping returns 'pong' displayed in HomePage, Zod validates all procedure inputs"
|
||||
},
|
||||
{
|
||||
"id": "US-004",
|
||||
"title": "App shell layout and sidebar navigation",
|
||||
"description": "As a user, I want a persistent left sidebar so that I can navigate between all sections of the app.",
|
||||
"acceptanceCriteria": [
|
||||
"Sidebar renders at 240px with #fafafa background and 1px right border (#e5e5e5)",
|
||||
"Nav items render with Lucide icons + labels: Home (house), Timeline (chart-gantt), Tasks (clipboard-check), Projects (folder-kanban)",
|
||||
"Active route highlights nav item with #f5f5f5 accent background (no extra border)",
|
||||
"Collapse button at bottom toggles sidebar to icon-only mode (64px wide); state persisted via electron-store",
|
||||
"TanStack Router renders the correct view component for each nav route: /, /timeline, /tasks, /projects",
|
||||
"Right-edge vertical rotated label 'keep scrolling for AI' with chevron-down icon is visible in every section as a non-interactive visual affordance",
|
||||
"Geist font applied globally via @fontsource/geist",
|
||||
"Global CSS variables set: bg=#ffffff, foreground=#0a0a0a, muted=#737373, border=#e5e5e5, sidebar=#fafafa, sidebar-accent=#f5f5f5, primary=#171717, primary-fg=#fafafa",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 4,
|
||||
"passes": true,
|
||||
"notes": "Completed: electron-store@8 sidebar collapse persistence via settings tRPC router, @fontsource/geist replacing Google Fonts CDN, right-edge 'keep scrolling for AI' label in all views, ESLint fixed with eslint-import-resolver-typescript"
|
||||
},
|
||||
{
|
||||
"id": "US-005",
|
||||
"title": "Client tRPC procedures (CRUD)",
|
||||
"description": "As a developer, I need tRPC procedures for client and sub-client CRUD so that the UI can create, read, update, and delete hierarchical client records.",
|
||||
"acceptanceCriteria": [
|
||||
"clients.list returns all clients ordered by name",
|
||||
"clients.create accepts { name: string, parentId?: string, industry?: string } and inserts with UUID and createdAt timestamp",
|
||||
"clients.update accepts { id: string, name?: string, industry?: string } and updates the record",
|
||||
"clients.delete accepts { id: string } and returns an error payload if the client has child clients or projects (does not delete)",
|
||||
"clients.deleteWithCascade accepts { id: string } and deletes the client, all descendant clients, and their projects (nulls projectId on orphaned tasks)",
|
||||
"All inputs validated with Zod schemas",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 5,
|
||||
"passes": true,
|
||||
"notes": "Completed: clients.list (ordered by name), clients.create (UUID + createdAt), clients.update (partial), clients.delete (guard returns error payload if children exist), clients.deleteWithCascade (BFS recursive — nulls orphaned tasks.projectId, deletes projects, then clients). All queries use .all()/.run() for drizzle better-sqlite3 sync driver."
|
||||
},
|
||||
{
|
||||
"id": "US-006",
|
||||
"title": "Project tRPC procedures (CRUD)",
|
||||
"description": "As a developer, I need tRPC procedures for project CRUD so that the UI can create, read, update, and archive projects attached to clients or as standalone.",
|
||||
"acceptanceCriteria": [
|
||||
"projects.list accepts optional { clientId?: string, includeArchived?: boolean } and returns matching projects",
|
||||
"projects.listAll returns all projects (for dropdowns) with id and name only",
|
||||
"projects.get accepts { id: string } and returns the full project record",
|
||||
"projects.create accepts { name: string, clientId?: string } and inserts with UUID, status='active', createdAt",
|
||||
"projects.update accepts { id: string, name?: string, clientId?: string, status?: 'active'|'archived', aiSummary?: string }",
|
||||
"projects.delete accepts { id: string } and deletes the project (nulls projectId on its tasks)",
|
||||
"All inputs validated with Zod",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 6,
|
||||
"passes": true,
|
||||
"notes": "Completed: projects.list (filters by clientId + includeArchived via drizzle and()), projects.listAll (id+name only), projects.get (returns null if not found), projects.create (UUID + status='active' + createdAt), projects.update (partial set object), projects.delete (nulls tasks.projectId then deletes project)"
|
||||
},
|
||||
{
|
||||
"id": "US-007",
|
||||
"title": "Task tRPC procedures (CRUD + filtering)",
|
||||
"description": "As a developer, I need tRPC procedures for task CRUD with search and filter support so that the global Tasks view can query tasks efficiently.",
|
||||
"acceptanceCriteria": [
|
||||
"tasks.list accepts { projectId?: string, status?: 'todo'|'in_progress'|'done', search?: string, orderBy?: 'dueDate'|'priority'|'createdAt' } and returns matching tasks",
|
||||
"tasks.list joins with projects and clients tables to return breadcrumb fields: projectName, clientName, subClientName",
|
||||
"tasks.create accepts { title: string, description?: string, status?: string, priority?: string, assignee?: string, dueDate?: number, projectId?: string }",
|
||||
"tasks.update accepts { id: string, ...partial task fields }",
|
||||
"tasks.delete accepts { id: string }",
|
||||
"All inputs validated with Zod",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 7,
|
||||
"passes": true,
|
||||
"notes": "Completed: tasks.list (LEFT JOIN projects+clients+parentClients for breadcrumb fields, and() filters for projectId/status/search via like(), orderBy CASE for priority), tasks.create (UUID + createdAt + defaults), tasks.update (partial set), tasks.delete. alias() from drizzle-orm/sqlite-core for self-join."
|
||||
},
|
||||
{
|
||||
"id": "US-008",
|
||||
"title": "Checkpoint and Note tRPC procedures (CRUD)",
|
||||
"description": "As a developer, I need tRPC procedures for checkpoints and notes so that the timeline and notes features have a typed backend.",
|
||||
"acceptanceCriteria": [
|
||||
"checkpoints.list accepts { projectId?: string } and returns matching checkpoints ordered by date",
|
||||
"checkpoints.create accepts { projectId: string, title: string, date: number, isAiSuggested?: number, isApproved?: number }",
|
||||
"checkpoints.update accepts { id: string, title?: string, date?: number, isApproved?: number }",
|
||||
"checkpoints.delete accepts { id: string }",
|
||||
"notes.list accepts { projectId?: string } and returns notes with id, title, createdAt, updatedAt — not content (for performance)",
|
||||
"notes.get accepts { id: string } and returns the full note including content",
|
||||
"notes.create accepts { title: string, content: string, projectId?: string }",
|
||||
"notes.update accepts { id: string, title?: string, content?: string } and always updates updatedAt",
|
||||
"notes.delete accepts { id: string }",
|
||||
"All inputs validated with Zod",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 8,
|
||||
"passes": true,
|
||||
"notes": "Completed: checkpoints.list (ordered by date, optional projectId filter), checkpoints.create (UUID + createdAt + defaults for isAiSuggested/isApproved), checkpoints.update (partial set), checkpoints.delete. notes.list (returns id/projectId/title/createdAt/updatedAt — no content), notes.get (full record or null), notes.create (UUID + createdAt + updatedAt), notes.update (partial set, always updates updatedAt), notes.delete."
|
||||
},
|
||||
{
|
||||
"id": "US-009",
|
||||
"title": "Project CRUD UI in Projects sidebar",
|
||||
"description": "As a user, I want to create, rename, and delete Projects from the Projects sidebar, where each project can optionally belong to a Client or Sub-Client.",
|
||||
"acceptanceCriteria": [
|
||||
"'New Project' button at top of Projects sidebar uses shadcn/ui Button component; creates a new project via clients.create tRPC mutation",
|
||||
"Each project item has a context menu using shadcn/ui DropdownMenu (triggered by kebab icon) with items: Rename, Delete",
|
||||
"Rename activates an inline editable field (shadcn/ui Input) replacing the label; pressing Enter or blurring saves via clients.update",
|
||||
"Delete shows a shadcn/ui AlertDialog confirmation; if the project has sub-projects, warns the user and offers cascade-delete option",
|
||||
"Each project can optionally be associated with a Client or Sub-Client",
|
||||
"Tree updates immediately after any mutation without full page reload",
|
||||
"All interactive elements use shadcn/ui primitives: install via 'npx shadcn@latest add button input dropdown-menu alert-dialog' before implementing",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 9,
|
||||
"passes": true,
|
||||
"notes": "Completed: ProjectSidebar component with New Project button (clients.create), kebab context menu (DropdownMenu with Rename/Delete/New Sub-Project), inline rename (Input with Enter/Escape/blur), AlertDialog delete with cascade-warn flow, collapsible tree with parent-child hierarchy, empty state. All shadcn/ui primitives: Button, Input, DropdownMenu, AlertDialog, Collapsible. Typecheck passes."
|
||||
},
|
||||
{
|
||||
"id": "US-010",
|
||||
"title": "Projects sidebar tree view and project detail routing",
|
||||
"description": "As a user, I want to see all projects in a collapsible tree in the sidebar, optionally grouped by client, and manage them from the Projects section.",
|
||||
"acceptanceCriteria": [
|
||||
"Tree renders projects as a flat list with folder icons; projects with a client show the client name as a grouping header; use shadcn/ui Collapsible for expand/collapse groups",
|
||||
"Search input at the top of the Projects sidebar uses shadcn/ui Input; filters the tree in real-time by project name",
|
||||
"Projects with no client appear under an 'Internal / No Client' group",
|
||||
"Project context menu uses shadcn/ui DropdownMenu with items: Edit (assign/change client), Archive/Unarchive, Delete",
|
||||
"Archived projects hidden by default; a shadcn/ui Switch or toggle reveals them",
|
||||
"Clicking a project node loads the Project Detail panel in the right pane",
|
||||
"Active project highlighted in tree",
|
||||
"Install shadcn/ui components via 'npx shadcn@latest add collapsible dialog select switch' before implementing",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 10,
|
||||
"passes": true,
|
||||
"notes": "Completed: ProjectSidebar reworked to show projects grouped by client (Collapsible groups), 'Internal / No Client' group for orphan projects, real-time search filter, archive toggle (Switch), context menu (Edit Client via Dialog+Select, Archive/Unarchive, Delete with AlertDialog), click selects project via search params, active project highlighted. ProjectDetail placeholder component. projects.update now accepts nullable clientId. shadcn/ui: dialog, select, switch installed."
|
||||
},
|
||||
{
|
||||
"id": "US-011",
|
||||
"title": "Global Tasks view UI",
|
||||
"description": "As a user, I want a global task list where I can create, filter, search, and update tasks across all projects in one place.",
|
||||
"acceptanceCriteria": [
|
||||
"4 stat cards using shadcn/ui Card (Card, CardHeader, CardTitle, CardContent) at top: Total Tasks, To Do, In Progress, Completed — each with a Lucide icon and count, reactively updated via tasks.list queries",
|
||||
"Search uses shadcn/ui Input; filters tasks by title or description (case-insensitive, 300ms debounce)",
|
||||
"Status filter uses shadcn/ui Tabs (Tabs, TabsList, TabsTrigger): All | To Do | In Progress | Completed",
|
||||
"'Order by' uses shadcn/ui DropdownMenu: Due Date | Priority | Created Date",
|
||||
"Task rows display: shadcn/ui Checkbox, title (bold 14px), description (muted 14px), priority chip using shadcn/ui Badge (HIGH=destructive variant, MEDIUM=secondary variant, LOW=outline variant with green), due date chip (calendar icon + 'Due Mon DD'), breadcrumb (Client > Sub-Client > Project, chevron-separated via shadcn/ui Breadcrumb if available), assignee (person icon + name)",
|
||||
"Completed task rows have green-tinted background (#f0fdf4 or similar)",
|
||||
"Clicking the shadcn/ui Checkbox calls tasks.update to set status='done' (or back to 'todo') immediately",
|
||||
"'New Task' shadcn/ui Button opens a shadcn/ui Dialog modal: shadcn/ui Input for title (required), Textarea for description, Select for priority, Popover+Calendar for due date, Select for project (optional searchable), Input for assignee (optional)",
|
||||
"Install shadcn/ui components via 'npx shadcn@latest add card tabs checkbox badge dialog textarea select popover calendar' before implementing",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 11,
|
||||
"passes": true,
|
||||
"notes": "Completed: Global Tasks view with 4 stat cards (Card, CardHeader, CardTitle, CardContent), search with 300ms debounce (Input + Search icon), status filter tabs (Tabs/TabsList/TabsTrigger: All/To Do/In Progress/Completed), Order by dropdown (DropdownMenu: Due Date/Priority/Created Date), task rows with Checkbox toggle (todo↔done), priority Badge (destructive/secondary/outline variants), due date chip, breadcrumb (Client > Sub-Client > Project), assignee. Completed rows green-tinted. NewTaskDialog component with title Input, Textarea description, Select priority/status, Popover+Calendar due date, Select project, Input assignee. All shadcn/ui primitives installed: card, tabs, checkbox, badge, textarea, popover, calendar."
|
||||
},
|
||||
{
|
||||
"id": "US-012",
|
||||
"title": "GanttChart SVG component and global Timeline view",
|
||||
"description": "As a user, I want to view and create timeline checkpoints on a Gantt-style view so that I have full control over project milestones.",
|
||||
"acceptanceCriteria": [
|
||||
"Reusable GanttChart component accepts { checkpoints: Checkpoint[], startDate: Date, endDate: Date } props",
|
||||
"Component renders a custom SVG: month labels on the X axis, a horizontal baseline <line>, and <circle> dots for each checkpoint positioned by date",
|
||||
"Dot fill: dark (#171717) = isApproved=1 + status todo, green (#16a34a) = done/approved, dashed outline = isApproved=0 (pending AI suggestion)",
|
||||
"A vertical 'Today' marker line rendered at the current date",
|
||||
"Component uses ResizeObserver for responsive SVG width",
|
||||
"Clicking a checkpoint dot opens a shadcn/ui Popover with: title, formatted date, and a shadcn/ui Button (variant=destructive, size=sm) for Delete (calls checkpoints.delete)",
|
||||
"Global Timeline route (/timeline) renders GanttChart with all checkpoints from all projects, color-coded or grouped by project",
|
||||
"'+ Add' shadcn/ui Button opens a shadcn/ui Dialog: shadcn/ui Input for title (required), Popover+Calendar for date picker (required), Select for project dropdown (required in global view)",
|
||||
"Install shadcn/ui components via 'npx shadcn@latest add popover calendar' before implementing (button, dialog, input, select already installed)",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 12,
|
||||
"passes": true,
|
||||
"notes": "Completed: Reusable GanttChart SVG component with month labels, baseline, ResizeObserver responsive width, Today marker (red line), checkpoint dots (dark=#171717 for future/approved, green=#16a34a for past/approved, dashed outline for pending AI suggestions). Popover on dot click shows title, date, project name, delete button. Global Timeline route (/timeline) renders all checkpoints from all projects with project name lookup via Map. AddCheckpointDialog with title Input, Popover+Calendar date, Select project. Legend showing dot types."
|
||||
},
|
||||
{
|
||||
"id": "US-013",
|
||||
"title": "Project Detail view — layout, breadcrumb, stat cards, AI summary",
|
||||
"description": "As a user, I want a project detail panel showing breadcrumb navigation, project name, stat cards, and an AI summary card.",
|
||||
"acceptanceCriteria": [
|
||||
"Right panel renders when a project is selected in the Projects tree",
|
||||
"Breadcrumb at top uses shadcn/ui Breadcrumb (Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbSeparator) showing Client > Sub-Client path",
|
||||
"Project name renders as H1 below the breadcrumb",
|
||||
"3 stat cards using shadcn/ui Card displayed horizontally: Notes (count from notes.list), Tasks Complete (done/total fraction from tasks.list), Checkpoints (approved/total fraction from checkpoints.list)",
|
||||
"AI Project Summary card uses shadcn/ui Card with sparkle (sparkles) Lucide icon + placeholder text 'AI summary will appear here' when project.aiSummary is null/empty",
|
||||
"When project.aiSummary is populated, the card displays the AI-generated text instead",
|
||||
"Install shadcn/ui components via 'npx shadcn@latest add breadcrumb' before implementing (card already installed)",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 13,
|
||||
"passes": true,
|
||||
"notes": "Completed: Project Detail view with Breadcrumb (Client > Sub-Client path from clients list), H1 project name, 3 stat cards (Notes count, Tasks Complete done/total, Checkpoints approved/total), AI Project Summary card with sparkles icon showing aiSummary or placeholder text. All data fetched via tRPC queries scoped to projectId. shadcn/ui breadcrumb installed."
|
||||
},
|
||||
{
|
||||
"id": "US-014",
|
||||
"title": "Kanban board in Project Detail",
|
||||
"description": "As a user, I want a Kanban board inside the project detail view with drag-and-drop task management between status columns.",
|
||||
"acceptanceCriteria": [
|
||||
"@hello-pangea/dnd installed; DragDropContext wraps 3 Droppable columns: To Do | In Progress | Completed",
|
||||
"Each task card is a Draggable wrapped in a shadcn/ui Card rendering: title, description (truncated), priority as shadcn/ui Badge, due date chip, assignee string",
|
||||
"Dragging a card to another column calls tasks.update({ id, status }) via tRPC and the UI updates immediately (optimistic or on success)",
|
||||
"'+ Add' shadcn/ui Button (variant=ghost, size=sm) in each column header opens the shadcn/ui Dialog new-task modal with the column's status pre-selected",
|
||||
"Columns show a task count in their header using shadcn/ui Badge (variant=secondary)",
|
||||
"All card content uses shadcn/ui primitives: Card, Badge, Button (already installed)",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 14,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-015",
|
||||
"title": "Inline project timeline and notes list in Project Detail",
|
||||
"description": "As a user, I want to see the project's Gantt timeline and a list of its notes within the project detail scrollable view.",
|
||||
"acceptanceCriteria": [
|
||||
"Project Detail view includes a 'Project Timeline' section using the GanttChart component (from US-012) scoped to the current project's checkpoints",
|
||||
"'+ Add' shadcn/ui Button (variant=outline, size=sm) in the timeline section header opens the add-checkpoint shadcn/ui Dialog with the project pre-selected",
|
||||
"Notes section below Kanban shows a flat list using shadcn/ui Separator between rows: each row has note title + formatted createdAt date",
|
||||
"'+ Add' shadcn/ui Button in notes header calls notes.create with a default title and navigates to /notes/:noteId",
|
||||
"Clicking a note title navigates to /notes/:noteId",
|
||||
"All buttons/dialogs use shadcn/ui components (already installed)",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 15,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-016",
|
||||
"title": "Milkdown note editor",
|
||||
"description": "As a user, I want a full-screen Markdown editor for each note so that I can write rich content without leaving the app.",
|
||||
"acceptanceCriteria": [
|
||||
"@milkdown/react and @milkdown/preset-commonmark installed; Milkdown editor renders at route /notes/:noteId",
|
||||
"Supported Markdown: headings (H1-H6), bold, italic, inline code, code blocks, bullet lists, ordered lists, blockquotes",
|
||||
"Note title editable as a shadcn/ui Input (variant borderless/ghost style) at the top of the page (separate from Milkdown content area)",
|
||||
"Content auto-saves to SQLite via notes.update on Milkdown onChange event, debounced 500ms",
|
||||
"Unsaved indicator shown using shadcn/ui Badge (variant=secondary, text 'Saving...') next to the title while save is pending",
|
||||
"Back button uses shadcn/ui Button (variant=ghost, size=icon) with ArrowLeft Lucide icon; navigates to the previous route",
|
||||
"All UI chrome uses shadcn/ui components (already installed)",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 16,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-017",
|
||||
"title": "Fluid Curtain pull-down animation",
|
||||
"description": "As a user, I want to pull down from the top of any view to slide the app panel off-screen and reveal the AI chat layer beneath.",
|
||||
"acceptanceCriteria": [
|
||||
"framer-motion useMotionValue + useSpring (stiffness: 300, damping: 30) controls a 'y' CSS transform on the main app panel wrapper",
|
||||
"Trigger 1: wheel event listener at document level — when the current route's scroll position is at 0 and deltaY < 0 (overscroll up), animate panel y from 0 to viewport height",
|
||||
"Trigger 2: Cmd/Ctrl+K keyboard shortcut toggles curtain open (y = viewport height) and closed (y = 0)",
|
||||
"AI chat view is rendered as a fixed full-screen layer behind the sliding panel and becomes fully visible when panel slides down",
|
||||
"App panel remains mounted during animation (no unmount/remount, no state loss)",
|
||||
"Returning from chat: wheel event with deltaY > 0 at chat-bottom OR Cmd/Ctrl+K slides panel back to y = 0",
|
||||
"Right-edge vertical 'keep scrolling for AI' label with chevron-down is visible in every section (non-interactive, visual hint only)",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 17,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-018",
|
||||
"title": "GitHub Copilot SDK setup and keytar token storage",
|
||||
"description": "As a developer, I need the GitHub Copilot SDK initialized in the main process with secure OS keychain token storage so that AI features can authenticate.",
|
||||
"acceptanceCriteria": [
|
||||
"keytar installed and imported in main process only (not renderer)",
|
||||
"ai.setToken tRPC mutation accepts { token: string } and stores it via keytar.setPassword('adiuva', 'copilot-token', token)",
|
||||
"ai.hasToken tRPC query returns a boolean indicating whether a token is stored",
|
||||
"On app start, main process reads the token from keychain and initializes the GitHub Copilot SDK client",
|
||||
"Settings dialog uses shadcn/ui Dialog (DialogTrigger as a SidebarMenuButton with Settings/gear icon in the sidebar footer); dialog content uses shadcn/ui Input for token paste + shadcn/ui Button to save via ai.setToken",
|
||||
"If no token is stored, AI-dependent features display a prompt using shadcn/ui Card with a shadcn/ui Button linking to the Settings dialog instead of throwing an error",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 18,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-019",
|
||||
"title": "@Orchestrator agent with intent routing",
|
||||
"description": "As a developer, I need an Orchestrator agent that receives user messages, reads intent, and routes to the correct specialist agent.",
|
||||
"acceptanceCriteria": [
|
||||
"ai.chat tRPC procedure accepts { message: string, context: { type: 'global' | 'project', projectId?: string } }",
|
||||
"@Orchestrator system prompt instructs the model to use one of three routing tool calls: route_to_project (when context is a project), route_to_knowledge (for cross-project questions), or route_to_general (for everything else)",
|
||||
"For project-scoped context, Orchestrator invokes @ProjectAgent logic and returns its response",
|
||||
"For global context, Orchestrator answers from task/project summaries directly",
|
||||
"Streaming tokens returned to renderer incrementally (use tRPC subscription or async generator pattern)",
|
||||
"SDK auth errors and timeouts caught; procedure returns { error: string } for user-facing display",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 19,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-020",
|
||||
"title": "Context-scoped AI chat UI",
|
||||
"description": "As a user, I want the AI chat (revealed by the Fluid Curtain) to display a context header, support message input, and stream AI responses.",
|
||||
"acceptanceCriteria": [
|
||||
"Chat panel shows a context header using shadcn/ui Badge (variant=outline): 'Chatting about: [Project Name]' when opened from a project detail view, or 'Global workspace' when opened from other sections",
|
||||
"Chat input box uses shadcn/ui Textarea: white background, border #d4d4d4, shadow-lg, min-height 109px, placeholder 'Ask me anything...'; Send uses shadcn/ui Button (black bg, Send Lucide icon + 'Send' label) anchored bottom-right",
|
||||
"User messages appear as right-aligned message bubbles using shadcn/ui Card; AI responses as left-aligned Cards",
|
||||
"Streaming: AI response tokens appended to the current AI bubble as they arrive from ai.chat",
|
||||
"A loading spinner or pulsing indicator (shadcn/ui Skeleton) shown while waiting for first token",
|
||||
"If ai.chat returns { error }, display the error message in a shadcn/ui Card with destructive border styling",
|
||||
"Chat history is session-only — cleared when the curtain closes or the app restarts",
|
||||
"Install shadcn/ui components via 'npx shadcn@latest add textarea' before implementing (card, badge, button, skeleton already installed)",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 20,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-021",
|
||||
"title": "@ProjectAgent with project action tools",
|
||||
"description": "As a user, I want the AI to answer project-specific questions and take actions like adding tasks, summarizing the project, and suggesting checkpoints.",
|
||||
"acceptanceCriteria": [
|
||||
"read_project_notes tool: fetches all notes for the scoped projectId from SQLite and returns combined content to the model",
|
||||
"add_task tool: creates a task in the project via tasks.create and confirms with 'Task added: [title]' in the chat response",
|
||||
"get_summary tool: calls the SDK to generate a 2-3 sentence summary of the project based on its notes and tasks, then calls projects.update to persist the result in project.aiSummary",
|
||||
"suggest_checkpoints tool: returns a JSON array of { title: string, date: string } proposed checkpoints based on date-anchored commitments found in notes",
|
||||
"@Orchestrator routes project-context messages to @ProjectAgent",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 21,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-022",
|
||||
"title": "LanceDB vector store setup and note embedding pipeline",
|
||||
"description": "As a developer, I need notes embedded into LanceDB so that semantic search across all project notes is possible.",
|
||||
"acceptanceCriteria": [
|
||||
"vectordb (LanceDB Node.js binding) installed and initialized in main process only; vector DB stored at app.getPath('userData')/vectors/",
|
||||
"After notes.create or notes.update, note content is embedded via the GitHub Copilot SDK embeddings endpoint and upserted in LanceDB with metadata: { noteId, projectId, content }",
|
||||
"On first app startup, a migration routine checks if the 'notes' LanceDB table exists; if not, embeds all existing SQLite notes and populates LanceDB",
|
||||
"Embedding errors are caught and logged to console (console.error) but do not reject the notes.update/create promise",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 22,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-023",
|
||||
"title": "@KnowledgeAgent semantic search across all projects",
|
||||
"description": "As a user, I want to ask questions that retrieve semantically relevant content from all past project notes regardless of project scope.",
|
||||
"acceptanceCriteria": [
|
||||
"vector_search_all tool accepts a query string and performs a LanceDB similarity search returning the top-5 results",
|
||||
"Each result includes: noteId, note title (joined from SQLite), projectId, project name (joined from SQLite), and matched text excerpt",
|
||||
"@Orchestrator routes cross-project knowledge queries to @KnowledgeAgent",
|
||||
"Chat response includes inline citations in the format: 'From: [Project Name] — [Note Title]'",
|
||||
"Typecheck passes"
|
||||
],
|
||||
"priority": 23,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-024",
|
||||
"title": "AI checkpoint suggestions UI",
|
||||
"description": "As a user, I want the AI to suggest timeline checkpoints from my meeting notes, which I can approve or reject directly in the timeline.",
|
||||
"acceptanceCriteria": [
|
||||
"'Suggest checkpoints' shadcn/ui Button (variant=outline, sparkles Lucide icon) in the Project Detail timeline header calls ai.chat with a suggest_checkpoints intent for the current project",
|
||||
"Suggested checkpoints returned by @ProjectAgent are inserted into the checkpoints table via checkpoints.create with isAiSuggested=1, isApproved=0",
|
||||
"Pending suggestions appear as shadcn/ui Card components (with dashed border via className 'border-dashed') above or below the GanttChart in the Project Detail timeline section",
|
||||
"'Approve' shadcn/ui Button (variant=default, size=sm) on each card calls checkpoints.update({ id, isApproved: 1 }); the checkpoint then appears as a normal dot on the Gantt",
|
||||
"'Reject' shadcn/ui Button (variant=ghost, size=sm) calls checkpoints.delete({ id }) and removes the card",
|
||||
"All UI uses shadcn/ui components (already installed)",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 24,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
},
|
||||
{
|
||||
"id": "US-025",
|
||||
"title": "Home dashboard — AI daily brief and suggestion chips",
|
||||
"description": "As a user, I want the Home screen to greet me with an AI-generated daily brief and pre-populated suggestion chips for quick queries.",
|
||||
"acceptanceCriteria": [
|
||||
"Greeting rendered as '✦ Hello, {name}' in Geist Semibold 30px with -1px letter-spacing; name sourced from electron-store (defaults to 'there' if not set)",
|
||||
"Top-right corner stat chip uses shadcn/ui Badge (variant=secondary) showing 'N Task due' where N = count of tasks with dueDate on or before end of today",
|
||||
"On app open, ai.chat called with global context to generate a daily brief paragraph highlighting tasks due today/this week and recent project activity",
|
||||
"Brief displayed below greeting in a shadcn/ui Card; bold key phrases rendered as <strong> (model wraps them in **markdown bold**)",
|
||||
"4 suggestion chips rendered in a 4-column flex row below the chat box using shadcn/ui Button (variant=outline); each chip has a Lucide icon + short prompt text",
|
||||
"Clicking a suggestion chip populates the chat input with the chip's prompt text",
|
||||
"Chat box uses shadcn/ui Textarea: white bg, border #d4d4d4, shadow-lg, min-height 109px, placeholder 'Ask me anything...'; Send uses shadcn/ui Button (black bg) bottom-right",
|
||||
"All UI uses shadcn/ui components (already installed)",
|
||||
"Typecheck passes",
|
||||
"Verify in browser using dev-browser skill"
|
||||
],
|
||||
"priority": 25,
|
||||
"passes": false,
|
||||
"notes": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
## Codebase Patterns
|
||||
- `alias(table, 'alias_name')` from `drizzle-orm/sqlite-core` enables self-joins (e.g., clients → parentClients for hierarchy)
|
||||
- `sql<T>\`CASE WHEN ... THEN ... ELSE ... END\`` for conditional SELECT fields (e.g., clientName vs subClientName based on parentId)
|
||||
- `or(like(col1, pattern), like(col2, pattern))` for multi-column search; SQLite LIKE on NULL columns safely returns NULL (falsy) so OR is safe
|
||||
- Vite configs use `.mts` extension (not `.ts`) to avoid ESM/CJS conflict with electron-forge's externalize-deps plugin
|
||||
- electron-trpc uses `exposeElectronTRPC()` in preload and `createIPCHandler({ router, windows })` in main; renderer uses `ipcLink()` from `electron-trpc/renderer`
|
||||
- appRouter lives at `src/main/router/index.ts`; renderer client at `src/renderer/lib/trpc.ts`
|
||||
- `@/*` path alias maps to `src/renderer/*` (configured in tsconfig.json paths)
|
||||
- Drizzle ORM with better-sqlite3 (sync driver): SELECT queries MUST end with `.all()` to execute; INSERT/UPDATE/DELETE MUST end with `.run()`
|
||||
- `inArray(column, values)` works with nullable columns when values is `string[]` (TypeScript covariance allows string[] → (string | null)[])
|
||||
- All DB tables use `CREATE TABLE IF NOT EXISTS` for non-destructive migrations
|
||||
- All IDs are UUIDs generated via `crypto.randomUUID()`
|
||||
- TypeScript strict mode + noUncheckedIndexedAccess enabled; always account for possible undefined on array access
|
||||
- electron-store@8 (CJS) used for app settings; use lazy init pattern `getStore()` like `getDb()` to avoid calling before app ready
|
||||
- ESLint uses `eslint-import-resolver-typescript` to resolve `@/*` aliases; configured in `.eslintrc.json` under `settings.import/resolver`
|
||||
- App settings (sidebar state, etc.) exposed via `settings` tRPC sub-router for type-safe renderer access
|
||||
- `z.string().nullable().optional()` in tRPC inputs enables three-state semantics: undefined = don't change, null = clear, string = set value
|
||||
- NewTaskDialog component at `src/renderer/components/tasks/NewTaskDialog.tsx` accepts `defaultProjectId` and `defaultStatus` props for reuse in Kanban column "+ Add" buttons
|
||||
- `date-fns` is available as a transitive dependency of `react-day-picker` (shadcn/ui calendar)
|
||||
- GanttChart component at `src/renderer/components/timeline/GanttChart.tsx` is reusable: accepts `defaultProjectId` to scope to a project (for US-015 inline timeline)
|
||||
- AddCheckpointDialog at `src/renderer/components/timeline/AddCheckpointDialog.tsx` accepts `defaultProjectId` — hides project select when provided
|
||||
- TanStack Router `validateSearch` with Zod schema for passing selected-item IDs via URL search params (e.g., `?projectId=...`)
|
||||
---
|
||||
|
||||
## 2026-02-19 - US-002
|
||||
- Installed `better-sqlite3`, `drizzle-orm` (runtime) and `@types/better-sqlite3`, `drizzle-kit` (dev)
|
||||
- Created `src/main/db/schema.ts`: 5 tables (clients, projects, tasks, checkpoints, notes) with exported InferSelectModel/InferInsertModel types
|
||||
- Created `src/main/db/index.ts`: `initDb()` opens/creates `adiuva.db` at `app.getPath('userData')`, runs CREATE TABLE IF NOT EXISTS (non-destructive), enables WAL mode; `getDb()` singleton accessor
|
||||
- Updated `src/main/index.ts`: call `initDb()` in `app.on('ready')`
|
||||
- Updated `vite.main.config.mts`: externalized `better-sqlite3`
|
||||
- Updated `forge.config.ts`: added `AutoUnpackNativesPlugin`
|
||||
- Added `drizzle.config.ts` for drizzle-kit CLI
|
||||
- Typecheck: passes with zero errors
|
||||
- **Learnings for future iterations:**
|
||||
- better-sqlite3 is CommonJS with native addon; Vite must NOT bundle it — always add to rollupOptions.external
|
||||
- The CREATE TABLE IF NOT EXISTS approach satisfies "never destructive" and works perfectly in electron without needing migration file resolution
|
||||
- electron-forge rebuilds native modules automatically on `electron-forge start`; no manual rebuild step needed
|
||||
- `app.getPath('userData')` is only available after `app.on('ready')` fires — do not call earlier
|
||||
---
|
||||
|
||||
## 2026-02-19 - US-008
|
||||
- What was implemented:
|
||||
- Full `checkpointsRouter` replacing stubs in `src/main/router/index.ts`
|
||||
- Full `notesRouter` replacing stubs in `src/main/router/index.ts`
|
||||
- Added `checkpoints` and `notes` to the schema import
|
||||
- `checkpoints.list`: optional `projectId` filter, ordered by `asc(checkpoints.date)`
|
||||
- `checkpoints.create`: inserts with UUID, createdAt=Date.now(), defaults isAiSuggested/isApproved to 0
|
||||
- `checkpoints.update`: partial set for title/date/isApproved
|
||||
- `checkpoints.delete`: deletes by id, returns `{ success: true }`
|
||||
- `notes.list`: returns `{ id, projectId, title, createdAt, updatedAt }` only — no content (performance)
|
||||
- `notes.get`: returns full record or null via `.all()[0] ?? null` pattern
|
||||
- `notes.create`: inserts with UUID, createdAt=updatedAt=Date.now()
|
||||
- `notes.update`: partial set, always sets updatedAt=Date.now() regardless of which fields changed
|
||||
- `notes.delete`: deletes by id, returns `{ success: true }`
|
||||
- Files changed: `src/main/router/index.ts`, `prd.json`, `progress.txt`
|
||||
- **Learnings for future iterations:**
|
||||
- `notes.update` must always set `updatedAt` — build the set object with updatedAt outside the conditional block
|
||||
- `notes.list` intentionally excludes `content` column for performance; use `notes.get` for full record
|
||||
- `checkpoints.projectId` is `.notNull()` in schema (unlike tasks.projectId which is nullable) — no null coalescing needed
|
||||
---
|
||||
|
||||
## 2026-02-19 - US-003
|
||||
- What was implemented:
|
||||
- Installed: electron-trpc, @trpc/server, @trpc/client, @trpc/react-query, @tanstack/react-query, zod
|
||||
- Created `src/main/router/index.ts` with full appRouter: stub routers for health, clients, projects, tasks, checkpoints, notes, ai
|
||||
- Updated `src/preload/index.ts` to call `exposeElectronTRPC()`
|
||||
- Updated `src/main/index.ts` to call `createIPCHandler({ router: appRouter, windows: [win] })`; `createWindow()` now returns `BrowserWindow`
|
||||
- Created `src/renderer/lib/trpc.ts` with `createTRPCReact<AppRouter>()`
|
||||
- Updated `src/renderer/index.tsx` to wrap app in `TRPCProvider` + `QueryClientProvider`
|
||||
- Updated `src/renderer/routes/index.tsx` to call `trpc.health.ping.useQuery()` and display 'tRPC IPC bridge: pong'
|
||||
- Files changed: package.json, package-lock.json, prd.json, src/main/index.ts, src/main/router/index.ts (new), src/preload/index.ts, src/renderer/index.tsx, src/renderer/lib/trpc.ts (new), src/renderer/routes/index.tsx
|
||||
- **Learnings for future iterations:**
|
||||
- electron-trpc `exposeElectronTRPC` is imported from `electron-trpc/main` (not a separate package)
|
||||
- `ipcLink` is imported from `electron-trpc/renderer` in the renderer process
|
||||
- `createTRPCReact<AppRouter>()` requires importing the AppRouter type from the main process router — this is a type-only import so it doesn't bundle main process code into renderer
|
||||
- The TRPCProvider must wrap QueryClientProvider (or be a sibling); both need the same queryClient instance
|
||||
- Stub routers return empty arrays or null — they will be replaced in US-005 through US-008
|
||||
---
|
||||
|
||||
## 2026-02-19 - US-004
|
||||
- What was implemented:
|
||||
- Installed: electron-store@8 (CJS-compatible, for persistent app settings), @fontsource/geist (self-hosted Geist font), eslint-import-resolver-typescript (ESLint path alias fix)
|
||||
- Created `src/main/store.ts` with lazy `getStore()` pattern using electron-store
|
||||
- Added `settings` tRPC sub-router with `getSidebarCollapsed` query and `setSidebarCollapsed` mutation
|
||||
- Updated `src/renderer/components/layout/AppShell.tsx` to: persist sidebar collapse via tRPC, add right-edge 'keep scrolling for AI' vertical label with ChevronDown icon
|
||||
- Updated `src/renderer/globals.css`: replaced Google Fonts CDN with @fontsource/geist imports (weights 400/500/600)
|
||||
- Updated `index.html`: removed Google Fonts CDN links
|
||||
- Updated `.eslintrc.json`: added eslint-import-resolver-typescript to fix @/* alias resolution (fixed all 7 pre-existing lint errors)
|
||||
- Files changed: .eslintrc.json, index.html, package.json, package-lock.json, src/main/router/index.ts, src/main/store.ts (new), src/renderer/components/layout/AppShell.tsx, src/renderer/globals.css
|
||||
- **Learnings for future iterations:**
|
||||
- Use electron-store@8 (not v9+) — v9+ is ESM-only and breaks with CommonJS main process
|
||||
- electron-store must NOT be initialized at module import time (before app.ready); use lazy `getStore()` like `getDb()` pattern
|
||||
- For sidebar/UI state loaded from IPC: use `localState ?? queryData ?? default` pattern to avoid flash while query resolves
|
||||
- @fontsource packages are the npm equivalent of Google Fonts — import weight-specific CSS files (e.g., `@fontsource/geist/400.css`)
|
||||
- ESLint `import/no-unresolved` requires `eslint-import-resolver-typescript` with `alwaysTryTypes: true` to resolve TypeScript path aliases
|
||||
- The `writingMode: 'vertical-rl'` + `transform: 'rotate(180deg)'` CSS pattern creates bottom-to-top text for vertical affordance labels
|
||||
---
|
||||
|
||||
## 2026-02-19 - US-006
|
||||
- What was implemented:
|
||||
- Full `projectsRouter` replacing stubs in `src/main/router/index.ts`
|
||||
- Added `and` to drizzle-orm imports
|
||||
- `projects.list`: uses `and()` with optional conditions for `clientId` filter and archived filter (defaults to active only)
|
||||
- `projects.listAll`: returns only `{ id, name }` columns for dropdown use
|
||||
- `projects.get`: `.all()` then `result[0] ?? null` pattern for nullable single-record lookup
|
||||
- `projects.create`: inserts with UUID, status='active', createdAt=Date.now()
|
||||
- `projects.update`: partial set object — only sets defined fields
|
||||
- `projects.delete`: nulls `tasks.projectId` for all tasks in the project, then deletes the project
|
||||
- Files changed: `src/main/router/index.ts`, `prd.json`, `progress.txt`
|
||||
- **Learnings for future iterations:**
|
||||
- `and(...conditions)` from drizzle-orm accepts `(SQL | undefined)[]` — pass `undefined` for optional conditions and drizzle filters them out automatically
|
||||
- For nullable single-record queries: use `.all()` and `result[0] ?? null` (strict mode forbids `.get()` direct null return without this pattern)
|
||||
- `and()` returns `SQL<unknown> | undefined` which `.where()` accepts directly (no extra wrapping needed)
|
||||
|
||||
---
|
||||
|
||||
## 2026-02-19 - US-005
|
||||
- What was implemented:
|
||||
- Full clients tRPC router replacing stubs in `src/main/router/index.ts`
|
||||
- Added imports: `eq`, `asc`, `inArray` from `drizzle-orm`; `getDb` from `../db`; `clients`, `projects`, `tasks` from `../db/schema`
|
||||
- `clients.list`: `db.select().from(clients).orderBy(asc(clients.name)).all()`
|
||||
- `clients.create`: inserts with `crypto.randomUUID()` + `Date.now()` via `.run()`
|
||||
- `clients.update`: partial update — only sets fields that are defined in input, skips if no-op
|
||||
- `clients.delete`: checks for child clients and child projects; returns `{ error: string }` payload if any exist; otherwise deletes and returns `{ success: true }`
|
||||
- `clients.deleteWithCascade`: BFS loop collects all descendant client IDs, finds their projects, nulls `projectId` on orphaned tasks, deletes projects, then deletes all clients
|
||||
- Files changed: `src/main/router/index.ts`, `prd.json`, `progress.txt`
|
||||
- **Learnings for future iterations:**
|
||||
- Drizzle ORM with better-sqlite3 sync driver: SELECT must call `.all()` to get an array; INSERT/UPDATE/DELETE must call `.run()` to execute — NOT calling these causes TypeScript errors (query builder ≠ result)
|
||||
- `inArray(nullableColumn, string[])` is TypeScript-safe because `string[]` is assignable to `(string | null)[]` via covariance
|
||||
- Guard against empty arrays before using `inArray` — while `allClientIds` is never empty (starts with input.id), `projectIds` could be empty; guarded with `if (projectIds.length > 0)` block
|
||||
- `@typescript-eslint/no-non-null-assertion` is configured as a warning (not error) in this project — `queue.shift()!` is fine after a `length > 0` check
|
||||
---
|
||||
|
||||
## 2026-02-19 - US-007
|
||||
- What was implemented:
|
||||
- Full `tasksRouter` replacing stubs in `src/main/router/index.ts`
|
||||
- Added imports: `or`, `like`, `sql` from `drizzle-orm`; `alias` from `drizzle-orm/sqlite-core`
|
||||
- `tasks.list`: LEFT JOINs projects → clients → parentClients (alias for self-join); CASE WHEN for clientName/subClientName breadcrumb fields; `and()` with optional conditions for projectId/status/search; `like()` OR search on title+description; CASE expression for priority ordering
|
||||
- `tasks.create`: inserts with UUID, defaults (status='todo', priority='medium'), createdAt=Date.now()
|
||||
- `tasks.update`: partial set object — only sets defined fields
|
||||
- `tasks.delete`: deletes by id, returns `{ success: true }`
|
||||
- Files changed: `src/main/router/index.ts`, `prd.json`, `progress.txt`
|
||||
- **Learnings for future iterations:**
|
||||
- `alias(table, 'alias_name')` is from `drizzle-orm/sqlite-core` (NOT `drizzle-orm`) for SQLite self-joins
|
||||
- `sql<T>\`CASE WHEN ${col} IS NOT NULL THEN ${alias.col} ELSE ${col} END\`` for conditional field selection using drizzle template literals
|
||||
- `or(like(col1, pattern), like(col2, pattern))` composes safely — null columns evaluate to NULL (falsy) in WHERE
|
||||
- For priority ordering: `asc(sql\`CASE ${tasks.priority} WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END\`)` puts high priority first
|
||||
---
|
||||
|
||||
## 2026-02-19 - US-009
|
||||
- What was implemented:
|
||||
- Verified existing `ProjectSidebar` component at `src/renderer/components/projects/ProjectSidebar.tsx` satisfies all US-009 acceptance criteria
|
||||
- New Project button at top using shadcn/ui Button + `clients.create` mutation with auto-rename on success
|
||||
- Kebab context menu (DropdownMenu) with Rename, New Sub-Project, Delete actions
|
||||
- Inline rename: Input replaces label, Enter saves via `clients.update`, Escape cancels, blur saves
|
||||
- Delete: AlertDialog with two stages — initial confirm, then cascade-warn if children exist (uses `clients.delete` first, falls back to `clients.deleteWithCascade`)
|
||||
- Hierarchical tree via `buildTree()` function (parent-child via `clients.parentId`)
|
||||
- Empty state with EmptyMedia + call-to-action button
|
||||
- All mutations invalidate `clients.list` query for immediate tree refresh
|
||||
- Typecheck passes (zero errors), lint passes (1 non-null assertion warning, guarded)
|
||||
- Files changed: `scripts/ralph/prd.json`, `scripts/ralph/progress.txt`
|
||||
- **Learnings for future iterations:**
|
||||
- The ProjectSidebar was built as part of US-004 app shell work but the US-009 story wasn't marked as passing — always check existing code before implementing
|
||||
- `useCallback` ref pattern (`ref={callbackRef}`) is used for auto-focus + select on mount without useEffect
|
||||
- The two-stage delete flow (try simple delete first → if error, show cascade option) maps well to the backend's `clients.delete` (guards) + `clients.deleteWithCascade` (force) pattern
|
||||
---
|
||||
|
||||
## 2026-02-19 - US-010
|
||||
- What was implemented:
|
||||
- Rewrote `ProjectSidebar` from a client-hierarchy tree to a project-centric sidebar grouped by client
|
||||
- Projects grouped by `clientId` using Collapsible headers; projects without a client appear under "Internal / No Client"
|
||||
- Search input filters projects by name in real-time (auto-expands all groups when searching)
|
||||
- Show/hide archived projects via Switch toggle (queries `projects.list` with `includeArchived`)
|
||||
- Context menu per project (DropdownMenu): Edit Client (Dialog + Select to assign/change/remove client), Archive/Unarchive, Delete (AlertDialog)
|
||||
- Clicking a project sets `projectId` in search params → renders ProjectDetail placeholder in right pane
|
||||
- Active project highlighted with `bg-sidebar-accent`
|
||||
- Updated `projects.update` tRPC procedure to accept `clientId: z.string().nullable().optional()` (allows unlinking from client)
|
||||
- Created placeholder `ProjectDetail` component (full implementation deferred to US-013)
|
||||
- Installed shadcn/ui: dialog, select, switch
|
||||
- Files changed: `src/renderer/components/projects/ProjectSidebar.tsx`, `src/renderer/routes/projects.tsx`, `src/renderer/components/projects/ProjectDetail.tsx` (new), `src/main/router/index.ts`, `src/renderer/components/ui/dialog.tsx` (new), `src/renderer/components/ui/select.tsx` (new), `src/renderer/components/ui/switch.tsx` (new), `scripts/ralph/prd.json`, `scripts/ralph/progress.txt`
|
||||
- **Learnings for future iterations:**
|
||||
- TanStack Router `validateSearch` with Zod schema is the cleanest way to pass selected-item IDs via URL search params without creating nested routes
|
||||
- `Route.useNavigate()` returns a typed navigate fn; use `void navigate({ search: { ... } })` to avoid unhandled promise warnings
|
||||
- For project grouping, query both `projects.list` and `clients.list` separately then join in-memory via a Map — avoids complex SQL joins for display-only data
|
||||
- `projects.update` with `clientId: z.string().nullable().optional()` allows three states: undefined (don't change), null (unlink), string (assign)
|
||||
- Auto-expanding all groups during search (`effectiveExpanded` computed from grouped keys) gives a better UX than forcing users to manually expand
|
||||
---
|
||||
|
||||
## 2026-02-20 - US-011
|
||||
- What was implemented:
|
||||
- Full Global Tasks view UI at `/tasks` route
|
||||
- 4 stat cards (Total Tasks, To Do, In Progress, Completed) using shadcn/ui Card components with Lucide icons, reactively updated from unfiltered `tasks.list` query
|
||||
- Search bar with 300ms debounce using shadcn/ui Input + Search icon
|
||||
- Status filter tabs using shadcn/ui Tabs (All | To Do | In Progress | Completed)
|
||||
- "Order by" dropdown using shadcn/ui DropdownMenu (Due Date | Priority | Created Date)
|
||||
- Task rows with: shadcn/ui Checkbox (toggles todo↔done), title (bold 14px), description (muted truncated), priority Badge (HIGH=destructive, MEDIUM=secondary, LOW=outline green), due date chip (calendar icon + formatted date), breadcrumb (Client > Sub-Client > Project with ChevronRight separators), assignee (User icon + name)
|
||||
- Completed task rows have green-tinted background (`bg-green-50 border-green-200`)
|
||||
- NewTaskDialog component with: Input for title (required), Textarea for description, Select for priority/status, Popover+Calendar for due date, Select for project (from `projects.listAll`), Input for assignee
|
||||
- Installed shadcn/ui components: card, tabs, checkbox, badge, textarea, popover, calendar
|
||||
- Files changed: `src/renderer/routes/tasks.tsx`, `src/renderer/components/tasks/NewTaskDialog.tsx` (new), `src/renderer/components/ui/card.tsx` (new), `src/renderer/components/ui/tabs.tsx` (new), `src/renderer/components/ui/checkbox.tsx` (new), `src/renderer/components/ui/badge.tsx` (new), `src/renderer/components/ui/textarea.tsx` (new), `src/renderer/components/ui/popover.tsx` (new), `src/renderer/components/ui/calendar.tsx` (new), `scripts/ralph/prd.json`, `scripts/ralph/progress.txt`
|
||||
- **Learnings for future iterations:**
|
||||
- Use two separate `tasks.list` queries: one unfiltered `{}` for stat card counts, one with filters for the displayed list — ensures stats always reflect total counts
|
||||
- `date-fns` `format(date, 'PPP')` produces "February 20th, 2026" style dates — already installed as a dependency of react-day-picker (shadcn/ui calendar)
|
||||
- shadcn/ui Select with an empty string value (`<SelectItem value="">No project</SelectItem>`) works as a "none" option for optional fields
|
||||
- The Popover+Calendar date picker pattern is standard shadcn/ui: Popover wraps a Button trigger showing the formatted date, PopoverContent contains the Calendar
|
||||
- Electron app runs at `http://localhost:5173` in dev mode but only within the Electron BrowserWindow — Playwright browser testing requires the Electron-specific test harness, not direct URL navigation
|
||||
---
|
||||
|
||||
## 2026-02-20 - US-012
|
||||
- What was implemented:
|
||||
- Reusable `GanttChart` SVG component at `src/renderer/components/timeline/GanttChart.tsx`
|
||||
- Accepts `{ checkpoints: GanttCheckpoint[], startDate: Date, endDate: Date, onDelete? }` props
|
||||
- Custom SVG rendering: month labels on X axis, horizontal baseline `<line>`, `<circle>` dots for checkpoints positioned by date
|
||||
- Dot fill logic: dark (#171717) for future approved checkpoints, green (#16a34a) for past approved, dashed outline (#737373) for pending AI suggestions (isApproved=0)
|
||||
- Vertical red "Today" marker line at current date
|
||||
- ResizeObserver for responsive SVG width
|
||||
- foreignObject + shadcn/ui Popover on each dot click: shows title, formatted date, project name, and destructive Delete button
|
||||
- `AddCheckpointDialog` component at `src/renderer/components/timeline/AddCheckpointDialog.tsx`: title Input (required), Popover+Calendar date (required), Select project dropdown (required in global view, hidden when `defaultProjectId` provided)
|
||||
- Global Timeline route (`/timeline`) renders GanttChart with all checkpoints, project name lookup via Map from `projects.listAll`
|
||||
- Legend showing dot types, empty state message when no checkpoints
|
||||
- Files changed: `src/renderer/components/timeline/GanttChart.tsx` (new), `src/renderer/components/timeline/AddCheckpointDialog.tsx` (new), `src/renderer/routes/timeline.tsx`
|
||||
- **Learnings for future iterations:**
|
||||
- `foreignObject` inside SVG is the cleanest way to embed React components (like Popover) on SVG elements — set `overflow-visible` class to prevent clipping
|
||||
- Checkpoints don't have a `status` field; use `isApproved=1` + `date < now` heuristic for "completed" vs "todo" dot color
|
||||
- Date range for the Gantt is computed dynamically: 1 month before earliest date, 2 months after latest date — ensures comfortable visual padding
|
||||
- GanttChart is designed for reuse: the `defaultProjectId` prop on AddCheckpointDialog pre-selects the project and hides the dropdown (for per-project timeline in US-015)
|
||||
- `trpc.projects.listAll.useQuery(undefined, { enabled: showProjectSelect })` prevents unnecessary queries when project is already known
|
||||
---
|
||||
@@ -1,113 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Ralph Wiggum - Long-running AI agent loop
|
||||
# Usage: ./ralph.sh [--tool amp|claude] [max_iterations]
|
||||
|
||||
set -e
|
||||
|
||||
# Parse arguments
|
||||
TOOL="claude" # Default to claude for backwards compatibility
|
||||
MAX_ITERATIONS=10
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--tool)
|
||||
TOOL="$2"
|
||||
shift 2
|
||||
;;
|
||||
--tool=*)
|
||||
TOOL="${1#*=}"
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
# Assume it's max_iterations if it's a number
|
||||
if [[ "$1" =~ ^[0-9]+$ ]]; then
|
||||
MAX_ITERATIONS="$1"
|
||||
fi
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Validate tool choice
|
||||
if [[ "$TOOL" != "amp" && "$TOOL" != "claude" ]]; then
|
||||
echo "Error: Invalid tool '$TOOL'. Must be 'amp' or 'claude'."
|
||||
exit 1
|
||||
fi
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PRD_FILE="$SCRIPT_DIR/prd.json"
|
||||
PROGRESS_FILE="$SCRIPT_DIR/progress.txt"
|
||||
ARCHIVE_DIR="$SCRIPT_DIR/archive"
|
||||
LAST_BRANCH_FILE="$SCRIPT_DIR/.last-branch"
|
||||
|
||||
# Archive previous run if branch changed
|
||||
if [ -f "$PRD_FILE" ] && [ -f "$LAST_BRANCH_FILE" ]; then
|
||||
CURRENT_BRANCH=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "")
|
||||
LAST_BRANCH=$(cat "$LAST_BRANCH_FILE" 2>/dev/null || echo "")
|
||||
|
||||
if [ -n "$CURRENT_BRANCH" ] && [ -n "$LAST_BRANCH" ] && [ "$CURRENT_BRANCH" != "$LAST_BRANCH" ]; then
|
||||
# Archive the previous run
|
||||
DATE=$(date +%Y-%m-%d)
|
||||
# Strip "ralph/" prefix from branch name for folder
|
||||
FOLDER_NAME=$(echo "$LAST_BRANCH" | sed 's|^ralph/||')
|
||||
ARCHIVE_FOLDER="$ARCHIVE_DIR/$DATE-$FOLDER_NAME"
|
||||
|
||||
echo "Archiving previous run: $LAST_BRANCH"
|
||||
mkdir -p "$ARCHIVE_FOLDER"
|
||||
[ -f "$PRD_FILE" ] && cp "$PRD_FILE" "$ARCHIVE_FOLDER/"
|
||||
[ -f "$PROGRESS_FILE" ] && cp "$PROGRESS_FILE" "$ARCHIVE_FOLDER/"
|
||||
echo " Archived to: $ARCHIVE_FOLDER"
|
||||
|
||||
# Reset progress file for new run
|
||||
echo "# Ralph Progress Log" > "$PROGRESS_FILE"
|
||||
echo "Started: $(date)" >> "$PROGRESS_FILE"
|
||||
echo "---" >> "$PROGRESS_FILE"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Track current branch
|
||||
if [ -f "$PRD_FILE" ]; then
|
||||
CURRENT_BRANCH=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "")
|
||||
if [ -n "$CURRENT_BRANCH" ]; then
|
||||
echo "$CURRENT_BRANCH" > "$LAST_BRANCH_FILE"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Initialize progress file if it doesn't exist
|
||||
if [ ! -f "$PROGRESS_FILE" ]; then
|
||||
echo "# Ralph Progress Log" > "$PROGRESS_FILE"
|
||||
echo "Started: $(date)" >> "$PROGRESS_FILE"
|
||||
echo "---" >> "$PROGRESS_FILE"
|
||||
fi
|
||||
|
||||
echo "Starting Ralph - Tool: $TOOL - Max iterations: $MAX_ITERATIONS"
|
||||
|
||||
for i in $(seq 1 $MAX_ITERATIONS); do
|
||||
echo ""
|
||||
echo "==============================================================="
|
||||
echo " Ralph Iteration $i of $MAX_ITERATIONS ($TOOL)"
|
||||
echo "==============================================================="
|
||||
|
||||
# Run the selected tool with the ralph prompt
|
||||
if [[ "$TOOL" == "amp" ]]; then
|
||||
OUTPUT=$(cat "$SCRIPT_DIR/prompt.md" | amp --dangerously-allow-all 2>&1 | tee /dev/stderr) || true
|
||||
else
|
||||
# Claude Code: use --dangerously-skip-permissions for autonomous operation, --print for output
|
||||
OUTPUT=$(claude --dangerously-skip-permissions --print < "$SCRIPT_DIR/CLAUDE.md" 2>&1 | tee /dev/stderr) || true
|
||||
fi
|
||||
|
||||
# Check for completion signal
|
||||
if echo "$OUTPUT" | grep -q "<promise>COMPLETE</promise>"; then
|
||||
echo ""
|
||||
echo "Ralph completed all tasks!"
|
||||
echo "Completed at iteration $i of $MAX_ITERATIONS"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Iteration $i complete. Continuing..."
|
||||
sleep 2
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Ralph reached max iterations ($MAX_ITERATIONS) without completing all tasks."
|
||||
echo "Check $PROGRESS_FILE for status."
|
||||
exit 1
|
||||
230
src/main/ai/chat-copilot.ts
Normal file
230
src/main/ai/chat-copilot.ts
Normal file
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* ChatCopilot — LangChain-compatible ChatModel adapter for the GitHub Copilot SDK.
|
||||
*
|
||||
* Wraps the CopilotClient's session API so it can be used as a drop-in
|
||||
* BaseChatModel within LangGraph, making the orchestrator provider-agnostic.
|
||||
*
|
||||
* Accepts a client-getter function to avoid module duplication issues when
|
||||
* this file is code-split into a separate chunk by Vite.
|
||||
*/
|
||||
import { SimpleChatModel, type BaseChatModelCallOptions } from '@langchain/core/language_models/chat_models';
|
||||
import type { BaseMessage } from '@langchain/core/messages';
|
||||
import { AIMessageChunk } from '@langchain/core/messages';
|
||||
import { ChatGenerationChunk } from '@langchain/core/outputs';
|
||||
import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
|
||||
import type { StructuredTool } from '@langchain/core/tools';
|
||||
|
||||
type CopilotClientType = import('@github/copilot-sdk').CopilotClient;
|
||||
|
||||
/** Minimal shape of a Copilot SDK Tool (avoids importing the full SDK type) */
|
||||
type CopilotNativeTool = {
|
||||
name: string;
|
||||
description?: string;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
parameters?: any;
|
||||
handler: (args: unknown) => Promise<unknown>;
|
||||
};
|
||||
|
||||
const COPILOT_TIMEOUT = 120_000;
|
||||
|
||||
export class ChatCopilot extends SimpleChatModel<BaseChatModelCallOptions> {
|
||||
private getClient: () => CopilotClientType | null;
|
||||
/** Native Copilot SDK tools, populated by bindTools() */
|
||||
private _copilotTools: CopilotNativeTool[] = [];
|
||||
|
||||
constructor(getClient: () => CopilotClientType | null, tools: CopilotNativeTool[] = []) {
|
||||
super({});
|
||||
this.getClient = getClient;
|
||||
this._copilotTools = tools;
|
||||
}
|
||||
|
||||
_llmType(): string {
|
||||
return 'copilot';
|
||||
}
|
||||
|
||||
private requireClient(): CopilotClientType {
|
||||
const client = this.getClient();
|
||||
if (!client) {
|
||||
throw new Error('CopilotClient not initialized. Please check that Copilot CLI is authenticated (copilot auth login).');
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert LangChain StructuredTools to Copilot SDK native tools and return a
|
||||
* new ChatCopilot instance that will pass them to createSession().
|
||||
* The SDK handles the full tool-calling loop internally — no LangChain ToolMessages needed.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
override bindTools(tools: StructuredTool[]): any {
|
||||
const copilotTools: CopilotNativeTool[] = tools.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description ?? undefined,
|
||||
parameters: t.schema,
|
||||
handler: async (args: unknown) => {
|
||||
console.log(`[ChatCopilot] tool handler called: ${t.name}`, JSON.stringify(args));
|
||||
const result = await t.invoke(args as Record<string, unknown>);
|
||||
const output = typeof result === 'string' ? result : JSON.stringify(result);
|
||||
console.log(`[ChatCopilot] tool handler result: ${t.name} →`, output.slice(0, 200));
|
||||
return output;
|
||||
},
|
||||
}));
|
||||
console.log(`[ChatCopilot] bindTools() called with:`, copilotTools.map((t) => t.name));
|
||||
return new ChatCopilot(this.getClient, copilotTools);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
async _call(messages: BaseMessage[], _options: this['ParsedCallOptions'], _runManager?: CallbackManagerForLLMRun): Promise<string> {
|
||||
const client = this.requireClient();
|
||||
|
||||
// Extract system message and user prompt from LangChain messages
|
||||
const systemContent = messages
|
||||
.filter((m) => m._getType() === 'system')
|
||||
.map((m) => (typeof m.content === 'string' ? m.content : ''))
|
||||
.join('\n');
|
||||
|
||||
const userContent = messages
|
||||
.filter((m) => m._getType() === 'human')
|
||||
.map((m) => (typeof m.content === 'string' ? m.content : ''))
|
||||
.join('\n');
|
||||
|
||||
const hasTools = this._copilotTools.length > 0;
|
||||
|
||||
const session = await client.createSession({
|
||||
// When tools are registered, use append mode so the SDK can inject its tool-calling
|
||||
// instructions before our content. mode:'replace' strips those SDK-managed sections,
|
||||
// causing the model to never see/call registered tools.
|
||||
systemMessage: systemContent
|
||||
? hasTools
|
||||
? { content: systemContent }
|
||||
: { mode: 'replace', content: systemContent }
|
||||
: undefined,
|
||||
// Pass native tools when available — SDK handles the agentic tool-calling loop
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
...(hasTools ? { tools: this._copilotTools as any[] } : { availableTools: [] }),
|
||||
streaming: false,
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await session.sendAndWait({ prompt: userContent }, COPILOT_TIMEOUT);
|
||||
return result?.data.content ?? '';
|
||||
} finally {
|
||||
await session.destroy().catch(() => { /* ignore cleanup errors */ });
|
||||
}
|
||||
}
|
||||
|
||||
async *_streamResponseChunks(
|
||||
messages: BaseMessage[],
|
||||
_options: this['ParsedCallOptions'],
|
||||
_runManager?: CallbackManagerForLLMRun,
|
||||
): AsyncGenerator<ChatGenerationChunk> {
|
||||
const client = this.requireClient();
|
||||
|
||||
const systemContent = messages
|
||||
.filter((m) => m._getType() === 'system')
|
||||
.map((m) => (typeof m.content === 'string' ? m.content : ''))
|
||||
.join('\n');
|
||||
|
||||
const userContent = messages
|
||||
.filter((m) => m._getType() === 'human')
|
||||
.map((m) => (typeof m.content === 'string' ? m.content : ''))
|
||||
.join('\n');
|
||||
|
||||
const hasTools = this._copilotTools.length > 0;
|
||||
|
||||
console.log(`[ChatCopilot] _streamResponseChunks: hasTools=${hasTools}, tools=[${this._copilotTools.map((t) => t.name).join(', ')}]`);
|
||||
console.log(`[ChatCopilot] systemMessage mode: ${hasTools ? 'append' : 'replace'}`);
|
||||
|
||||
const session = await client.createSession({
|
||||
// Same append-vs-replace logic as _call: tools require append mode so the SDK
|
||||
// can inject its tool-calling instructions before our project context.
|
||||
systemMessage: systemContent
|
||||
? hasTools
|
||||
? { content: systemContent }
|
||||
: { mode: 'replace', content: systemContent }
|
||||
: undefined,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
...(hasTools ? { tools: this._copilotTools as any[] } : { availableTools: [] }),
|
||||
streaming: true,
|
||||
});
|
||||
|
||||
console.log(`[ChatCopilot] session created: ${session.sessionId}`);
|
||||
|
||||
// Buffer chunks via event listener and yield them
|
||||
const chunks: string[] = [];
|
||||
let done = false;
|
||||
let sessionError: Error | null = null;
|
||||
let resolveNext: (() => void) | null = null;
|
||||
|
||||
const unsubDelta = session.on('assistant.message_delta', (event) => {
|
||||
const delta = event.data.deltaContent;
|
||||
if (delta) {
|
||||
chunks.push(delta);
|
||||
resolveNext?.();
|
||||
}
|
||||
});
|
||||
|
||||
const unsubEnd = session.on('session.idle', () => {
|
||||
console.log('[ChatCopilot] session.idle received');
|
||||
done = true;
|
||||
resolveNext?.();
|
||||
});
|
||||
|
||||
const unsubError = session.on('session.error', (event) => {
|
||||
console.error('[ChatCopilot] session.error received:', event.data.message);
|
||||
sessionError = new Error(event.data.message);
|
||||
done = true;
|
||||
resolveNext?.();
|
||||
});
|
||||
|
||||
// Log all events to understand SDK behaviour with tools
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const unsubAll = session.on((event: any) => {
|
||||
if (!['assistant.message_delta'].includes(event.type)) {
|
||||
console.log(`[ChatCopilot] SDK event: ${event.type}`, JSON.stringify(event.data ?? {}).slice(0, 300));
|
||||
}
|
||||
});
|
||||
|
||||
// Fire the request (don't await — we'll drain via events).
|
||||
const sendPromise = session.sendAndWait({ prompt: userContent }, COPILOT_TIMEOUT);
|
||||
|
||||
// If sendAndWait rejects before any session events fire (e.g. send() throws
|
||||
// internally due to a listModels/auth failure), wake up the while loop so it
|
||||
// doesn't hang waiting for session.idle that will never arrive.
|
||||
sendPromise.catch((err: unknown) => {
|
||||
if (!done) {
|
||||
sessionError = err instanceof Error ? err : new Error(String(err));
|
||||
done = true;
|
||||
resolveNext?.();
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
while (!done || chunks.length > 0) {
|
||||
if (chunks.length > 0) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const text = chunks.shift()!;
|
||||
const chunk = new ChatGenerationChunk({
|
||||
message: new AIMessageChunk({ content: text }),
|
||||
text,
|
||||
});
|
||||
await _runManager?.handleLLMNewToken(text);
|
||||
yield chunk;
|
||||
} else if (!done) {
|
||||
await new Promise<void>((resolve) => {
|
||||
resolveNext = resolve;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Propagate any error surfaced via session.error event or sendAndWait rejection
|
||||
if (sessionError) throw sessionError;
|
||||
} finally {
|
||||
unsubDelta();
|
||||
unsubEnd();
|
||||
unsubError();
|
||||
unsubAll();
|
||||
await session.destroy().catch(() => { /* ignore cleanup errors */ });
|
||||
}
|
||||
}
|
||||
}
|
||||
61
src/main/ai/copilot.ts
Normal file
61
src/main/ai/copilot.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { app } from 'electron';
|
||||
import { registerProvider, type AIProvider } from './provider';
|
||||
|
||||
// Dynamic import type — @github/copilot-sdk is ESM-only
|
||||
type CopilotClientType = import('@github/copilot-sdk').CopilotClient;
|
||||
|
||||
let client: CopilotClientType | null = null;
|
||||
let isReady = false;
|
||||
|
||||
const copilotProvider: AIProvider = {
|
||||
name: 'copilot',
|
||||
displayName: 'GitHub Copilot',
|
||||
usesExternalAuth: true,
|
||||
|
||||
async initialize(): Promise<boolean> {
|
||||
try {
|
||||
// Stop existing client if re-initializing
|
||||
if (client) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
await client.stop().catch(() => {});
|
||||
client = null;
|
||||
}
|
||||
|
||||
const { CopilotClient } = await import('@github/copilot-sdk');
|
||||
// No githubToken — uses stored OAuth credentials from Copilot CLI
|
||||
// (authenticate first with `copilot auth login`)
|
||||
client = new CopilotClient({
|
||||
autoStart: true,
|
||||
autoRestart: true,
|
||||
logLevel: 'warning',
|
||||
});
|
||||
await client.start();
|
||||
isReady = true;
|
||||
console.log('[AI] CopilotClient started (using CLI OAuth credentials)');
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('[AI] Failed to start CopilotClient:', err);
|
||||
client = null;
|
||||
isReady = false;
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
isReady(): boolean {
|
||||
return isReady && client !== null;
|
||||
},
|
||||
};
|
||||
|
||||
/** Get the CopilotClient instance (null if not initialized). */
|
||||
export function getCopilotClient(): CopilotClientType | null {
|
||||
return client;
|
||||
}
|
||||
|
||||
// Clean shutdown on app quit
|
||||
app.on('before-quit', () => {
|
||||
if (client) {
|
||||
client.stop().catch((err: unknown) => console.error('[AI] Error stopping CopilotClient:', err));
|
||||
}
|
||||
});
|
||||
|
||||
registerProvider(copilotProvider);
|
||||
73
src/main/ai/embeddings.ts
Normal file
73
src/main/ai/embeddings.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { getToken } from './token';
|
||||
|
||||
interface CopilotConfig {
|
||||
copilot_tokens?: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the GitHub Copilot OAuth token from the CLI config file.
|
||||
* Stored at ~/.copilot/config.json under copilot_tokens["{host}:{login}"].
|
||||
* Returns the first available token, or null if unavailable.
|
||||
*/
|
||||
function readCopilotToken(): string | null {
|
||||
try {
|
||||
const raw = fs.readFileSync(
|
||||
path.join(os.homedir(), '.copilot', 'config.json'),
|
||||
'utf-8',
|
||||
);
|
||||
const cfg = JSON.parse(raw) as CopilotConfig;
|
||||
const vals = Object.values(cfg.copilot_tokens ?? {});
|
||||
return vals[0] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed a single text string using the best available credentials.
|
||||
*
|
||||
* Priority:
|
||||
* 1. GitHub Copilot CLI token → OpenAI-compatible embeddings endpoint at
|
||||
* https://api.githubcopilot.com
|
||||
* 2. Stored OpenAI token → standard OpenAI embeddings API
|
||||
*
|
||||
* Throws if no credentials are available or the API call fails.
|
||||
* Callers must .catch() this and handle the error without rejecting
|
||||
* the surrounding tRPC mutation.
|
||||
*/
|
||||
export async function embedText(text: string): Promise<number[]> {
|
||||
const { OpenAIEmbeddings } = await import('@langchain/openai');
|
||||
|
||||
const copilotToken = readCopilotToken();
|
||||
|
||||
let embeddingsInstance;
|
||||
if (copilotToken) {
|
||||
embeddingsInstance = new OpenAIEmbeddings({
|
||||
apiKey: copilotToken,
|
||||
model: 'text-embedding-3-small',
|
||||
configuration: { baseURL: 'https://api.githubcopilot.com' },
|
||||
});
|
||||
} else {
|
||||
const openaiToken = await getToken('openai');
|
||||
if (!openaiToken) {
|
||||
throw new Error(
|
||||
'[Embeddings] No credentials available. Authenticate with Copilot CLI or add an OpenAI token in Settings.',
|
||||
);
|
||||
}
|
||||
embeddingsInstance = new OpenAIEmbeddings({
|
||||
apiKey: openaiToken,
|
||||
model: 'text-embedding-3-small',
|
||||
});
|
||||
}
|
||||
|
||||
// embedDocuments returns number[][] — cast explicitly to satisfy strict TS
|
||||
const results = (await embeddingsInstance.embedDocuments([text])) as number[][];
|
||||
const vector = results[0] as number[] | undefined;
|
||||
if (!vector || vector.length === 0) {
|
||||
throw new Error('[Embeddings] Empty vector returned from embedding API');
|
||||
}
|
||||
return vector;
|
||||
}
|
||||
81
src/main/ai/llm.ts
Normal file
81
src/main/ai/llm.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* LLM connector factory — returns a LangChain BaseChatModel for the active provider.
|
||||
*
|
||||
* The agent orchestration (LangGraph) is provider-independent. This module is
|
||||
* the only place that knows how to create provider-specific LLM instances.
|
||||
*/
|
||||
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
import { getActiveProviderName, getActiveProvider } from './provider';
|
||||
import { getToken } from './token';
|
||||
import { getCopilotClient } from './copilot';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Provider-specific factory functions (lazy-loaded)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function createOpenAIModel(token: string): Promise<BaseChatModel> {
|
||||
const { ChatOpenAI } = await import('@langchain/openai');
|
||||
return new ChatOpenAI({
|
||||
apiKey: token,
|
||||
model: 'gpt-4o-mini',
|
||||
temperature: 0.3,
|
||||
streaming: true,
|
||||
});
|
||||
}
|
||||
|
||||
async function createAnthropicModel(token: string): Promise<BaseChatModel> {
|
||||
const { ChatAnthropic } = await import('@langchain/anthropic');
|
||||
return new ChatAnthropic({
|
||||
apiKey: token,
|
||||
model: 'claude-sonnet-4-20250514',
|
||||
temperature: 0.3,
|
||||
streaming: true,
|
||||
});
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
async function createCopilotModel(_token: string): Promise<BaseChatModel> {
|
||||
// GitHub Copilot uses the Copilot SDK subprocess for auth and API access.
|
||||
// We wrap it in a LangChain-compatible adapter.
|
||||
// Pass getCopilotClient from this chunk (same as copilot.ts) to avoid
|
||||
// module duplication when chat-copilot.ts is code-split by Vite.
|
||||
const { ChatCopilot } = await import('./chat-copilot');
|
||||
return new ChatCopilot(getCopilotClient);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const MODEL_FACTORIES: Record<string, (token: string) => Promise<BaseChatModel>> = {
|
||||
openai: createOpenAIModel,
|
||||
anthropic: createAnthropicModel,
|
||||
copilot: createCopilotModel,
|
||||
};
|
||||
|
||||
/**
|
||||
* Get a LangChain BaseChatModel for the currently active AI provider.
|
||||
* Returns null if no provider is configured or no token is available.
|
||||
*/
|
||||
export async function getLLM(): Promise<BaseChatModel | null> {
|
||||
const providerName = getActiveProviderName();
|
||||
const factory = MODEL_FACTORIES[providerName];
|
||||
if (!factory) {
|
||||
console.log(`[AI] No LLM factory for provider "${providerName}"`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const provider = getActiveProvider();
|
||||
const token = provider?.usesExternalAuth ? '' : await getToken(providerName);
|
||||
if (!provider?.usesExternalAuth && !token) {
|
||||
console.log(`[AI] No token available for provider "${providerName}"`);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return await factory(token ?? '');
|
||||
} catch (err) {
|
||||
console.error(`[AI] Failed to create LLM for "${providerName}":`, err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
991
src/main/ai/orchestrator.ts
Normal file
991
src/main/ai/orchestrator.ts
Normal file
@@ -0,0 +1,991 @@
|
||||
/**
|
||||
* @Orchestrator agent — LangGraph-based intent routing.
|
||||
*
|
||||
* The agent logic (routing, state) lives here and is fully LLM-agnostic.
|
||||
* The LLM is a swappable connector obtained via `getLLM()`.
|
||||
*/
|
||||
import { Annotation, StateGraph, START, END } from '@langchain/langgraph';
|
||||
import { SystemMessage, HumanMessage, AIMessage, ToolMessage, type BaseMessage, type ToolCall } from '@langchain/core/messages';
|
||||
import { tool, type StructuredTool } from '@langchain/core/tools';
|
||||
import { eq, asc } from 'drizzle-orm';
|
||||
import { z } from 'zod';
|
||||
import { getDb } from '../db';
|
||||
import { projects, tasks, checkpoints, notes, clients } from '../db/schema';
|
||||
import { getLLM } from './llm';
|
||||
import { getActiveProviderName } from './provider';
|
||||
import { searchNotes, type SearchResult } from '../db/vectordb';
|
||||
|
||||
/**
|
||||
* Providers with tool calling support.
|
||||
* OpenAI/Anthropic: LangChain bindTools + ToolMessage agent loop.
|
||||
* Copilot: ChatCopilot.bindTools() converts to SDK-native tools; the SDK handles
|
||||
* the agentic loop internally so tool_calls is always [] on the response.
|
||||
*/
|
||||
const TOOL_CALLING_PROVIDERS = new Set(['openai', 'anthropic', 'copilot']);
|
||||
|
||||
const AI_STREAM_CHANNEL = 'ai:stream';
|
||||
const AI_ACTION_CHANNEL = 'ai:action';
|
||||
|
||||
/** Module-level sender ref — set at the start of orchestrate() so tool closures can emit actions. */
|
||||
let currentSender: Electron.WebContents | undefined;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface OrchestrateInput {
|
||||
message: string;
|
||||
context: { type: 'global' | 'project'; projectId?: string; uiContext?: string };
|
||||
sender?: Electron.WebContents;
|
||||
}
|
||||
|
||||
interface OrchestrateResult {
|
||||
response: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Context assembly (DB queries — provider-independent)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildProjectContext(projectId: string): string {
|
||||
const db = getDb();
|
||||
|
||||
const project = db.select().from(projects).where(eq(projects.id, projectId)).all()[0];
|
||||
if (!project) return 'Project not found.';
|
||||
|
||||
let clientName = '';
|
||||
if (project.clientId) {
|
||||
const client = db.select().from(clients).where(eq(clients.id, project.clientId)).all()[0];
|
||||
if (client) clientName = client.name;
|
||||
}
|
||||
|
||||
const projectTasks = db
|
||||
.select({ title: tasks.title, status: tasks.status, priority: tasks.priority, dueDate: tasks.dueDate })
|
||||
.from(tasks)
|
||||
.where(eq(tasks.projectId, projectId))
|
||||
.orderBy(asc(tasks.createdAt))
|
||||
.all();
|
||||
|
||||
const projectCheckpoints = db
|
||||
.select({ title: checkpoints.title, date: checkpoints.date, isApproved: checkpoints.isApproved })
|
||||
.from(checkpoints)
|
||||
.where(eq(checkpoints.projectId, projectId))
|
||||
.orderBy(asc(checkpoints.date))
|
||||
.all();
|
||||
|
||||
const projectNotes = db
|
||||
.select({ title: notes.title, content: notes.content })
|
||||
.from(notes)
|
||||
.where(eq(notes.projectId, projectId))
|
||||
.orderBy(asc(notes.createdAt))
|
||||
.all();
|
||||
|
||||
const lines: string[] = [
|
||||
`## Project: ${project.name}`,
|
||||
clientName ? `Client: ${clientName}` : '',
|
||||
`Status: ${project.status ?? 'active'}`,
|
||||
project.aiSummary ? `AI Summary: ${project.aiSummary}` : '',
|
||||
'',
|
||||
`### Tasks (${projectTasks.length})`,
|
||||
...projectTasks.map((t) => {
|
||||
const due = t.dueDate ? new Date(t.dueDate).toLocaleDateString() : 'no due date';
|
||||
return `- [${t.status}] ${t.title} (${t.priority}, ${due})`;
|
||||
}),
|
||||
'',
|
||||
`### Checkpoints (${projectCheckpoints.length})`,
|
||||
...projectCheckpoints.map((c) => {
|
||||
const approved = c.isApproved ? 'approved' : 'pending';
|
||||
return `- ${c.title} — ${new Date(c.date).toLocaleDateString()} (${approved})`;
|
||||
}),
|
||||
'',
|
||||
`### Notes (${projectNotes.length})`,
|
||||
...projectNotes.map((n) => {
|
||||
const excerpt = n.content.length > 500 ? n.content.slice(0, 500) + '…' : n.content;
|
||||
return `#### ${n.title}\n${excerpt}`;
|
||||
}),
|
||||
];
|
||||
|
||||
return lines.filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
function buildGlobalContext(): string {
|
||||
const db = getDb();
|
||||
|
||||
const allProjects = db
|
||||
.select({ id: projects.id, name: projects.name, status: projects.status })
|
||||
.from(projects)
|
||||
.where(eq(projects.status, 'active'))
|
||||
.orderBy(asc(projects.name))
|
||||
.all();
|
||||
|
||||
const allTasks = db.select().from(tasks).all();
|
||||
const todoCount = allTasks.filter((t) => t.status === 'todo').length;
|
||||
const inProgressCount = allTasks.filter((t) => t.status === 'in_progress').length;
|
||||
const doneCount = allTasks.filter((t) => t.status === 'done').length;
|
||||
|
||||
const now = Date.now();
|
||||
const weekFromNow = now + 7 * 24 * 60 * 60 * 1000;
|
||||
const upcomingTasks = allTasks
|
||||
.filter((t) => t.dueDate && t.dueDate >= now && t.dueDate <= weekFromNow && t.status !== 'done')
|
||||
.sort((a, b) => (a.dueDate ?? 0) - (b.dueDate ?? 0));
|
||||
|
||||
const projectMap = new Map(allProjects.map((p) => [p.id, p.name]));
|
||||
|
||||
const lines: string[] = [
|
||||
`## Workspace Overview`,
|
||||
`Active projects: ${allProjects.length}`,
|
||||
`Tasks: ${allTasks.length} total (${todoCount} todo, ${inProgressCount} in progress, ${doneCount} done)`,
|
||||
'',
|
||||
`### Active Projects`,
|
||||
...allProjects.map((p) => `- ${p.name}`),
|
||||
'',
|
||||
`### Tasks Due This Week (${upcomingTasks.length})`,
|
||||
...upcomingTasks.map((t) => {
|
||||
const projectName = t.projectId ? (projectMap.get(t.projectId) ?? 'Unknown') : 'No project';
|
||||
const due = t.dueDate ? new Date(t.dueDate).toLocaleDateString() : '';
|
||||
return `- ${t.title} [${projectName}] — due ${due}`;
|
||||
}),
|
||||
];
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Project action tools (built per-invocation, scoped to a project)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildProjectTools(projectId: string): StructuredTool[] {
|
||||
const db = getDb();
|
||||
|
||||
const readProjectNotesTool = tool(
|
||||
async (_input: Record<string, never>) => {
|
||||
const projectNotes = db
|
||||
.select({ title: notes.title, content: notes.content })
|
||||
.from(notes)
|
||||
.where(eq(notes.projectId, projectId))
|
||||
.orderBy(asc(notes.createdAt))
|
||||
.all();
|
||||
if (projectNotes.length === 0) return 'No notes found for this project.';
|
||||
return projectNotes.map((n) => `### ${n.title}\n${n.content}`).join('\n\n---\n\n');
|
||||
},
|
||||
{
|
||||
name: 'read_project_notes',
|
||||
description:
|
||||
'Fetches the full content of all notes for this project from the database. Use this when the user asks a detailed question about project notes or decisions.',
|
||||
schema: z.object({}),
|
||||
},
|
||||
);
|
||||
|
||||
const addTaskTool = tool(
|
||||
async (input: { title: string; description?: string; priority?: string; dueDate?: string }) => {
|
||||
const id = crypto.randomUUID();
|
||||
db.insert(tasks)
|
||||
.values({
|
||||
id,
|
||||
title: input.title,
|
||||
description: input.description ?? null,
|
||||
status: 'todo',
|
||||
priority: input.priority ?? 'medium',
|
||||
dueDate: input.dueDate ? new Date(input.dueDate).getTime() : null,
|
||||
projectId,
|
||||
isAiSuggested: 1,
|
||||
createdAt: Date.now(),
|
||||
})
|
||||
.run();
|
||||
sendAction(currentSender, { type: 'task_created', taskId: id });
|
||||
return `Task added: ${input.title}`;
|
||||
},
|
||||
{
|
||||
name: 'add_task',
|
||||
description:
|
||||
"Creates a new task in this project. Use when the user asks to add, create, or log a task. Returns 'Task added: [title]' on success.",
|
||||
schema: z.object({
|
||||
title: z.string().describe('Task title (required)'),
|
||||
description: z.string().optional().describe('Optional longer description'),
|
||||
priority: z.enum(['low', 'medium', 'high']).optional().describe('Task priority, defaults to medium'),
|
||||
dueDate: z.string().optional().describe('ISO 8601 date or datetime string — include the time when specified, e.g. 2026-03-15 or 2026-03-15T17:00:00'),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const getSummaryTool = tool(
|
||||
async (_input: Record<string, never>) => {
|
||||
const contextData = buildProjectContext(projectId);
|
||||
const summaryLlm = await getLLM();
|
||||
if (!summaryLlm) return 'Error: AI provider not available to generate summary.';
|
||||
const result = await summaryLlm.invoke([
|
||||
new SystemMessage(
|
||||
'Generate a concise 2-3 sentence project summary based on the data below. ' +
|
||||
'Focus on current status, key tasks, and notable milestones. Be direct and factual.',
|
||||
),
|
||||
new HumanMessage(contextData),
|
||||
]);
|
||||
const summary = typeof result.content === 'string' ? result.content : '';
|
||||
db.update(projects).set({ aiSummary: summary }).where(eq(projects.id, projectId)).run();
|
||||
return summary;
|
||||
},
|
||||
{
|
||||
name: 'get_summary',
|
||||
description:
|
||||
'Generates a 2-3 sentence AI summary of the project based on its notes and tasks, ' +
|
||||
'then saves it to the project record (project.aiSummary). Returns the summary text.',
|
||||
schema: z.object({}),
|
||||
},
|
||||
);
|
||||
|
||||
const suggestCheckpointsTool = tool(
|
||||
async (_input: Record<string, never>) => {
|
||||
const contextData = buildProjectContext(projectId);
|
||||
const suggestionLlm = await getLLM();
|
||||
if (!suggestionLlm) return '[]';
|
||||
const result = await suggestionLlm.invoke([
|
||||
new SystemMessage(
|
||||
'You are a project planning assistant. Analyze the project data below and extract ' +
|
||||
'date-anchored commitments from the notes (e.g. "deliver X by March 15", "review on April 2").\n\n' +
|
||||
'Return ONLY a valid JSON array of objects with shape { "title": string, "date": string } ' +
|
||||
'where date is ISO 8601 format (YYYY-MM-DD). Return [] if no date-anchored commitments are found.\n\n' +
|
||||
'Example: [{"title":"Client review","date":"2026-03-15"},{"title":"Beta launch","date":"2026-04-01"}]',
|
||||
),
|
||||
new HumanMessage(contextData),
|
||||
]);
|
||||
const content = typeof result.content === 'string' ? result.content.trim() : '[]';
|
||||
// Extract JSON array from response (model may wrap in markdown)
|
||||
const match = content.match(/\[[\s\S]*\]/);
|
||||
const jsonStr = match ? match[0] : '[]';
|
||||
try {
|
||||
const parsed = JSON.parse(jsonStr) as Array<{ title: string; date: string }>;
|
||||
for (const s of parsed) {
|
||||
const ts = new Date(s.date).getTime();
|
||||
if (Number.isNaN(ts)) continue;
|
||||
db.insert(checkpoints).values({
|
||||
id: crypto.randomUUID(),
|
||||
projectId,
|
||||
title: s.title,
|
||||
date: ts,
|
||||
isAiSuggested: 1,
|
||||
isApproved: 0,
|
||||
createdAt: Date.now(),
|
||||
}).run();
|
||||
}
|
||||
sendAction(currentSender, { type: 'checkpoints_suggested', count: parsed.length });
|
||||
return jsonStr;
|
||||
} catch {
|
||||
return '[]';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'suggest_checkpoints',
|
||||
description:
|
||||
'Analyzes project notes for date-anchored commitments and returns a JSON array of ' +
|
||||
'{ title: string, date: string } suggested checkpoints. Use when the user asks for timeline or milestone suggestions.',
|
||||
schema: z.object({}),
|
||||
},
|
||||
);
|
||||
|
||||
const suggestTasksTool = tool(
|
||||
async (_input: Record<string, never>) => {
|
||||
const contextData = buildProjectContext(projectId);
|
||||
const suggestionLlm = await getLLM();
|
||||
if (!suggestionLlm) return '[]';
|
||||
const result = await suggestionLlm.invoke([
|
||||
new SystemMessage(
|
||||
'You are a project planning assistant. Analyze the project data below and extract ' +
|
||||
'actionable tasks from the notes (e.g. "set up CI pipeline", "draft proposal for client").\n\n' +
|
||||
'Return ONLY a valid JSON array of objects with shape { "title": string, "description"?: string, "priority"?: "low"|"medium"|"high", "dueDate"?: string } ' +
|
||||
'where dueDate is ISO 8601 format (YYYY-MM-DD) if mentioned. Return [] if no actionable tasks are found.\n\n' +
|
||||
'Example: [{"title":"Set up CI pipeline","description":"Configure GitHub Actions for automated testing","priority":"high"},{"title":"Draft client proposal","dueDate":"2026-03-20"}]',
|
||||
),
|
||||
new HumanMessage(contextData),
|
||||
]);
|
||||
const content = typeof result.content === 'string' ? result.content.trim() : '[]';
|
||||
const match = content.match(/\[[\s\S]*\]/);
|
||||
const jsonStr = match ? match[0] : '[]';
|
||||
try {
|
||||
const parsed = JSON.parse(jsonStr) as Array<{ title: string; description?: string; priority?: string; dueDate?: string }>;
|
||||
for (const s of parsed) {
|
||||
db.insert(tasks).values({
|
||||
id: crypto.randomUUID(),
|
||||
projectId,
|
||||
title: s.title,
|
||||
description: s.description ?? null,
|
||||
status: 'todo',
|
||||
priority: s.priority ?? 'medium',
|
||||
assignee: null,
|
||||
dueDate: s.dueDate ? new Date(s.dueDate).getTime() : null,
|
||||
isAiSuggested: 1,
|
||||
isApproved: 0,
|
||||
createdAt: Date.now(),
|
||||
}).run();
|
||||
}
|
||||
sendAction(currentSender, { type: 'tasks_suggested', count: parsed.length });
|
||||
return jsonStr;
|
||||
} catch {
|
||||
return '[]';
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'suggest_tasks',
|
||||
description:
|
||||
'Analyzes project notes for actionable tasks and returns a JSON array of ' +
|
||||
'{ title: string, description?: string, priority?: string, dueDate?: string } suggested tasks. ' +
|
||||
'Use when the user asks for task suggestions.',
|
||||
schema: z.object({}),
|
||||
},
|
||||
);
|
||||
|
||||
return [readProjectNotesTool, addTaskTool, getSummaryTool, suggestCheckpointsTool, suggestTasksTool] as StructuredTool[];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Global action tools (workspace-level, no project scope required)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildGlobalTools(): StructuredTool[] {
|
||||
const db = getDb();
|
||||
|
||||
const addTaskTool = tool(
|
||||
async (input: { title: string; description?: string; priority?: string; dueDate?: string; projectId?: string }) => {
|
||||
const id = crypto.randomUUID();
|
||||
db.insert(tasks)
|
||||
.values({
|
||||
id,
|
||||
title: input.title,
|
||||
description: input.description ?? null,
|
||||
status: 'todo',
|
||||
priority: input.priority ?? 'medium',
|
||||
dueDate: input.dueDate ? new Date(input.dueDate).getTime() : null,
|
||||
projectId: input.projectId ?? null,
|
||||
isAiSuggested: 1,
|
||||
createdAt: Date.now(),
|
||||
})
|
||||
.run();
|
||||
sendAction(currentSender, { type: 'task_created', taskId: id });
|
||||
return `Task added: ${input.title}`;
|
||||
},
|
||||
{
|
||||
name: 'add_task',
|
||||
description:
|
||||
"Creates a new task in the workspace. Use when the user asks to add, create, or register a task. " +
|
||||
"Returns 'Task added: [title]' on success.",
|
||||
schema: z.object({
|
||||
title: z.string().describe('Task title (required)'),
|
||||
description: z.string().optional().describe('Optional longer description'),
|
||||
priority: z.enum(['low', 'medium', 'high']).optional().describe('Task priority, defaults to medium'),
|
||||
dueDate: z.string().optional().describe('ISO 8601 date or datetime string — include the time when specified, e.g. 2026-03-15 or 2026-03-15T17:00:00'),
|
||||
projectId: z.string().optional().describe('Optional project ID to associate the task with'),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
return [addTaskTool] as StructuredTool[];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Knowledge tools (cross-project vector search)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildKnowledgeTools(): StructuredTool[] {
|
||||
const db = getDb();
|
||||
|
||||
const vectorSearchAllTool = tool(
|
||||
async (input: { query: string }) => {
|
||||
const results: SearchResult[] = await searchNotes(input.query, 5);
|
||||
|
||||
if (results.length === 0) {
|
||||
return 'No matching notes found across projects.';
|
||||
}
|
||||
|
||||
const enriched = results.map((r) => {
|
||||
const noteRow = db
|
||||
.select({ title: notes.title })
|
||||
.from(notes)
|
||||
.where(eq(notes.id, r.id))
|
||||
.all()[0];
|
||||
|
||||
let projectName = 'No project';
|
||||
if (r.projectId) {
|
||||
const projectRow = db
|
||||
.select({ name: projects.name })
|
||||
.from(projects)
|
||||
.where(eq(projects.id, r.projectId))
|
||||
.all()[0];
|
||||
if (projectRow) projectName = projectRow.name;
|
||||
}
|
||||
|
||||
const title = noteRow?.title ?? 'Untitled';
|
||||
const excerpt =
|
||||
r.content.length > 300 ? r.content.slice(0, 300) + '…' : r.content;
|
||||
|
||||
return [
|
||||
`**From: ${projectName} — ${title}**`,
|
||||
`Note ID: ${r.id} | Project ID: ${r.projectId}`,
|
||||
excerpt,
|
||||
].join('\n');
|
||||
});
|
||||
|
||||
return enriched.join('\n\n---\n\n');
|
||||
},
|
||||
{
|
||||
name: 'vector_search_all',
|
||||
description:
|
||||
'Performs a semantic search across ALL project notes in the workspace. ' +
|
||||
'Returns the top 5 most relevant notes with their project name, note title, and a text excerpt. ' +
|
||||
'Use this tool whenever the user asks a cross-project knowledge question.',
|
||||
schema: z.object({
|
||||
query: z.string().describe('The search query to find relevant notes across all projects'),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
return [vectorSearchAllTool] as StructuredTool[];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// System prompts
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeProjectAgentPrompt(contextData: string, withTools = true, uiContext?: string): string {
|
||||
const toolsSection = withTools ? `
|
||||
You also have access to the following tools — use them proactively when appropriate:
|
||||
- read_project_notes: Fetch full untruncated note content. Use for detailed note questions.
|
||||
- add_task: Create a new task in this project. Use when the user asks to add a task.
|
||||
- get_summary: Generate and save a 2-3 sentence project summary. Use when asked to summarize.
|
||||
- suggest_checkpoints: Extract date-based milestone suggestions from notes. Use for timeline/checkpoint questions.
|
||||
- suggest_tasks: Extract actionable task suggestions from notes. Use when the user asks for task suggestions.
|
||||
|
||||
When suggest_checkpoints or suggest_tasks returns a JSON array, present the items in a readable bullet-point format.` : '';
|
||||
|
||||
return `You are @ProjectAgent, an AI assistant specialized in a specific project within Adiuva.
|
||||
|
||||
You have access to the following project data:
|
||||
|
||||
${contextData}
|
||||
${toolsSection}
|
||||
Answer the user's question based on this project context. Be concise and helpful.
|
||||
When referencing tasks, notes, or checkpoints, mention them by name.
|
||||
If you don't have enough information, say so.${uiContext ? `\nThe user is currently viewing the "${uiContext}" section of the UI.\nIf your response relates to a different section (e.g., user asks about checkpoints while viewing Tasks), prefix your response with [SECTION:<section-id>] where section-id matches one of: project-summary, project-timeline, project-tasks, project-notes, tasks-overview, tasks-list, timeline-chart, note-editor.\nOnly use this prefix when the answer clearly belongs in a different section than where the user currently is.` : ''}`;
|
||||
}
|
||||
|
||||
function makeGeneralAgentPrompt(contextData: string, withTools = true, uiContext?: string): string {
|
||||
const toolsSection = withTools ? `
|
||||
You also have access to the following tools — use them proactively when appropriate:
|
||||
- add_task: Create a new task. Use whenever the user asks to add, register, or note a to-do item or task.
|
||||
|
||||
When creating a task from a user request, infer a clear title and set dueDate if a specific date/time is mentioned.` : '';
|
||||
|
||||
return `You are @GeneralAgent, an AI assistant for the Adiuva workspace.
|
||||
|
||||
You have access to the following workspace data:
|
||||
|
||||
${contextData}
|
||||
${toolsSection}
|
||||
Help the user with their question based on this workspace context. Provide concise, actionable answers.
|
||||
When discussing tasks or projects, reference them by name.${uiContext ? `\nThe user is currently viewing the "${uiContext}" section of the UI.\nIf your response relates to a different section (e.g., user asks about checkpoints while viewing Tasks), prefix your response with [SECTION:<section-id>] where section-id matches one of: project-summary, project-timeline, project-tasks, project-notes, tasks-overview, tasks-list, timeline-chart, note-editor.\nOnly use this prefix when the answer clearly belongs in a different section than where the user currently is.` : ''}`;
|
||||
}
|
||||
|
||||
function makeKnowledgeAgentPrompt(contextData: string, withTools = true, uiContext?: string): string {
|
||||
const toolsSection = withTools ? `
|
||||
You have access to the following tools — use them proactively:
|
||||
- vector_search_all: Performs semantic search across ALL project notes. Always use this tool when the user asks a knowledge question. Pass the user's question (or a refined version) as the query.
|
||||
|
||||
IMPORTANT: After receiving search results, format your response with inline citations.
|
||||
For each piece of information you reference, include the citation in this exact format:
|
||||
From: [Project Name] — [Note Title]
|
||||
|
||||
Example:
|
||||
"The team decided to use React for the frontend. (From: Website Redesign — Tech Stack Decision)"` : '';
|
||||
|
||||
return `You are @KnowledgeAgent, an AI assistant that searches across all project knowledge in Adiuva.
|
||||
|
||||
You have access to the following workspace data:
|
||||
|
||||
${contextData}
|
||||
${toolsSection}
|
||||
Your primary job is to find and synthesize information from notes across all projects.
|
||||
Always use the vector_search_all tool to search for relevant notes before answering.
|
||||
If no results are found, say so clearly.${uiContext ? `\nThe user is currently viewing the "${uiContext}" section of the UI.\nIf your response relates to a different section (e.g., user asks about checkpoints while viewing Tasks), prefix your response with [SECTION:<section-id>] where section-id matches one of: project-summary, project-timeline, project-tasks, project-notes, tasks-overview, tasks-list, timeline-chart, note-editor.\nOnly use this prefix when the answer clearly belongs in a different section than where the user currently is.` : ''}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// LangGraph State
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const OrchestratorState = Annotation.Root({
|
||||
/** The user's original message */
|
||||
userMessage: Annotation<string>(),
|
||||
/** Chat context (global vs project-scoped) */
|
||||
chatContext: Annotation<{ type: 'global' | 'project'; projectId?: string; uiContext?: string }>(),
|
||||
/** The route chosen by the orchestrator */
|
||||
route: Annotation<'project' | 'knowledge' | 'general'>(),
|
||||
/** Messages for the specialist agent */
|
||||
messages: Annotation<BaseMessage[]>({
|
||||
reducer: (existing, incoming) =>
|
||||
Array.isArray(incoming) ? existing.concat(incoming) : existing.concat([incoming]),
|
||||
default: () => [],
|
||||
}),
|
||||
/** The final response text */
|
||||
response: Annotation<string>(),
|
||||
});
|
||||
|
||||
type State = typeof OrchestratorState.State;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Graph nodes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Node 1: Classify intent — always calls the LLM for every provider */
|
||||
async function classifyIntent(state: State): Promise<Partial<State>> {
|
||||
const llm = await getLLM();
|
||||
if (!llm) throw new Error('AI provider not configured. Please add your token in Settings.');
|
||||
|
||||
const response = await llm.invoke([
|
||||
new SystemMessage(
|
||||
`You are a routing classifier for Adiuva, a project management workspace.
|
||||
Classify the user's message into exactly one category. Reply with ONLY the category name, nothing else.
|
||||
|
||||
Categories:
|
||||
- project: Question about a specific project (tasks, notes, checkpoints, progress, summaries)
|
||||
- knowledge: Cross-project or historical question (e.g., "what did we decide about X?", "find notes about Y")
|
||||
- general: Everything else (general help, scheduling, task overviews, workspace summaries)`,
|
||||
),
|
||||
new HumanMessage(state.userMessage),
|
||||
]);
|
||||
|
||||
const text = (typeof response.content === 'string' ? response.content : '').trim().toLowerCase();
|
||||
const validRoutes = ['project', 'knowledge', 'general'] as const;
|
||||
const route = validRoutes.find((r) => text.includes(r)) ?? 'general';
|
||||
|
||||
console.log(`[Orchestrator] classifyIntent → route="${route}" (raw="${text}")`);
|
||||
return { route };
|
||||
}
|
||||
|
||||
/** Node 2a: Project agent — tools-enabled agentic loop for project-scoped questions */
|
||||
async function projectAgent(state: State): Promise<Partial<State>> {
|
||||
const llm = await getLLM();
|
||||
if (!llm) throw new Error('AI provider not configured.');
|
||||
|
||||
const projectId = state.chatContext.projectId;
|
||||
|
||||
// If no projectId in context, delegate to generalAgent
|
||||
if (!projectId) {
|
||||
return generalAgent(state);
|
||||
}
|
||||
|
||||
const contextData = buildProjectContext(projectId);
|
||||
|
||||
// Only providers with real tool calling support use the agent loop.
|
||||
const supportsTools = TOOL_CALLING_PROVIDERS.has(getActiveProviderName());
|
||||
|
||||
console.log(`[Orchestrator] projectAgent: provider="${getActiveProviderName()}", supportsTools=${supportsTools}, projectId=${projectId}`);
|
||||
|
||||
// Copilot tools are registered natively via the SDK (createSession({ tools })).
|
||||
// Including text tool descriptions in the system prompt causes the model to output
|
||||
// XML <tool_call> blocks instead of using the SDK's API-level mechanism.
|
||||
const includeToolsInPrompt = supportsTools && getActiveProviderName() !== 'copilot';
|
||||
const uiContext = state.chatContext.uiContext;
|
||||
const systemPrompt = makeProjectAgentPrompt(contextData, includeToolsInPrompt, uiContext);
|
||||
|
||||
if (!supportsTools) {
|
||||
console.log('[Orchestrator] projectAgent: using context-only fallback (no tool support)');
|
||||
// Providers without any tool calling support: answer from context data only
|
||||
const response = await llm.invoke([
|
||||
new SystemMessage(systemPrompt),
|
||||
new HumanMessage(state.userMessage),
|
||||
]);
|
||||
const content = typeof response.content === 'string' ? response.content : '';
|
||||
return { messages: [response], response: content };
|
||||
}
|
||||
|
||||
// Build tools scoped to this projectId
|
||||
const projectTools = buildProjectTools(projectId);
|
||||
|
||||
console.log(`[Orchestrator] projectAgent: binding ${projectTools.length} tools: [${projectTools.map((t) => t.name).join(', ')}]`);
|
||||
|
||||
// Bind tools: OpenAI/Anthropic use LangChain's bindTools (ToolMessage loop);
|
||||
// Copilot uses ChatCopilot.bindTools() which registers tools with the SDK natively.
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const llmWithTools = llm.bindTools!(projectTools);
|
||||
|
||||
// Agent loop: invoke LLM → execute tool calls → repeat until no tool_calls
|
||||
const MAX_ITERATIONS = 5;
|
||||
const messageHistory: BaseMessage[] = [
|
||||
new SystemMessage(systemPrompt),
|
||||
new HumanMessage(state.userMessage),
|
||||
];
|
||||
|
||||
for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
|
||||
const response = await llmWithTools.invoke(messageHistory);
|
||||
messageHistory.push(response);
|
||||
|
||||
// Extract tool calls using type guard (no unsafe cast needed)
|
||||
const toolCalls: ToolCall[] = AIMessage.isInstance(response) ? (response.tool_calls ?? []) : [];
|
||||
|
||||
console.log(`[Orchestrator] agent loop iteration=${iteration}: tool_calls=[${toolCalls.map((c) => c.name).join(', ')}], content="${String(typeof response.content === 'string' ? response.content : '').slice(0, 100)}"`);
|
||||
|
||||
// No tool calls → LLM produced a final text response
|
||||
if (toolCalls.length === 0) {
|
||||
const content = typeof response.content === 'string' ? response.content : '';
|
||||
return { messages: messageHistory, response: content };
|
||||
}
|
||||
|
||||
// Execute each tool call and append ToolMessages to history
|
||||
for (const toolCall of toolCalls) {
|
||||
const matched = projectTools.find((t) => t.name === toolCall.name);
|
||||
if (!matched) {
|
||||
messageHistory.push(
|
||||
new ToolMessage({
|
||||
content: `Error: tool "${toolCall.name}" is not available.`,
|
||||
tool_call_id: toolCall.id ?? crypto.randomUUID(),
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Invoke with the ToolCall object — StructuredTool.invoke() detects _isToolCall()
|
||||
// and extracts args internally (same pattern used by LangGraph's own ToolNode).
|
||||
const output = await matched.invoke({ ...toolCall, type: 'tool_call' as const });
|
||||
const resultContent = typeof output === 'string' ? output : JSON.stringify(output);
|
||||
|
||||
messageHistory.push(
|
||||
new ToolMessage({
|
||||
content: resultContent,
|
||||
tool_call_id: toolCall.id ?? crypto.randomUUID(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Exceeded max iterations: extract last AI response text as best-effort fallback
|
||||
const lastAiMsg = [...messageHistory].reverse().find((m) => AIMessage.isInstance(m));
|
||||
const fallbackContent =
|
||||
lastAiMsg && typeof lastAiMsg.content === 'string' ? lastAiMsg.content : '';
|
||||
return { messages: messageHistory, response: fallbackContent };
|
||||
}
|
||||
|
||||
/** Node 2b: Knowledge agent — cross-project semantic search */
|
||||
async function knowledgeAgent(state: State): Promise<Partial<State>> {
|
||||
const llm = await getLLM();
|
||||
if (!llm) throw new Error('AI provider not configured.');
|
||||
|
||||
const contextData = buildGlobalContext();
|
||||
|
||||
const supportsTools = TOOL_CALLING_PROVIDERS.has(getActiveProviderName());
|
||||
const includeToolsInPrompt = supportsTools && getActiveProviderName() !== 'copilot';
|
||||
const uiContext = state.chatContext.uiContext;
|
||||
const systemPrompt = makeKnowledgeAgentPrompt(contextData, includeToolsInPrompt, uiContext);
|
||||
|
||||
console.log(`[Orchestrator] knowledgeAgent: provider="${getActiveProviderName()}", supportsTools=${supportsTools}`);
|
||||
|
||||
if (!supportsTools) {
|
||||
const response = await llm.invoke([
|
||||
new SystemMessage(systemPrompt),
|
||||
new HumanMessage(state.userMessage),
|
||||
]);
|
||||
const content = typeof response.content === 'string' ? response.content : '';
|
||||
return { messages: [response], response: content };
|
||||
}
|
||||
|
||||
const knowledgeTools = buildKnowledgeTools();
|
||||
|
||||
console.log(`[Orchestrator] knowledgeAgent: binding ${knowledgeTools.length} tools: [${knowledgeTools.map((t) => t.name).join(', ')}]`);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const llmWithTools = llm.bindTools!(knowledgeTools);
|
||||
|
||||
const MAX_ITERATIONS = 5;
|
||||
const messageHistory: BaseMessage[] = [
|
||||
new SystemMessage(systemPrompt),
|
||||
new HumanMessage(state.userMessage),
|
||||
];
|
||||
|
||||
for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
|
||||
const response = await llmWithTools.invoke(messageHistory);
|
||||
messageHistory.push(response);
|
||||
|
||||
const toolCalls: ToolCall[] = AIMessage.isInstance(response) ? (response.tool_calls ?? []) : [];
|
||||
|
||||
console.log(`[Orchestrator] knowledgeAgent loop iteration=${iteration}: tool_calls=[${toolCalls.map((c) => c.name).join(', ')}], content="${String(typeof response.content === 'string' ? response.content : '').slice(0, 100)}"`);
|
||||
|
||||
if (toolCalls.length === 0) {
|
||||
const content = typeof response.content === 'string' ? response.content : '';
|
||||
return { messages: messageHistory, response: content };
|
||||
}
|
||||
|
||||
for (const toolCall of toolCalls) {
|
||||
const matched = knowledgeTools.find((t) => t.name === toolCall.name);
|
||||
if (!matched) {
|
||||
messageHistory.push(
|
||||
new ToolMessage({
|
||||
content: `Error: tool "${toolCall.name}" is not available.`,
|
||||
tool_call_id: toolCall.id ?? crypto.randomUUID(),
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const output = await matched.invoke({ ...toolCall, type: 'tool_call' as const });
|
||||
const resultContent = typeof output === 'string' ? output : JSON.stringify(output);
|
||||
|
||||
messageHistory.push(
|
||||
new ToolMessage({
|
||||
content: resultContent,
|
||||
tool_call_id: toolCall.id ?? crypto.randomUUID(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const lastAiMsg = [...messageHistory].reverse().find((m) => AIMessage.isInstance(m));
|
||||
const fallbackContent =
|
||||
lastAiMsg && typeof lastAiMsg.content === 'string' ? lastAiMsg.content : '';
|
||||
return { messages: messageHistory, response: fallbackContent };
|
||||
}
|
||||
|
||||
/** Node 2c: General agent — workspace-wide questions and global task actions */
|
||||
async function generalAgent(state: State): Promise<Partial<State>> {
|
||||
const llm = await getLLM();
|
||||
if (!llm) throw new Error('AI provider not configured.');
|
||||
|
||||
const contextData = buildGlobalContext();
|
||||
|
||||
const supportsTools = TOOL_CALLING_PROVIDERS.has(getActiveProviderName());
|
||||
const includeToolsInPrompt = supportsTools && getActiveProviderName() !== 'copilot';
|
||||
const uiContext = state.chatContext.uiContext;
|
||||
const systemPrompt = makeGeneralAgentPrompt(contextData, includeToolsInPrompt, uiContext);
|
||||
|
||||
console.log(`[Orchestrator] generalAgent: provider="${getActiveProviderName()}", supportsTools=${supportsTools}`);
|
||||
|
||||
if (!supportsTools) {
|
||||
const response = await llm.invoke([
|
||||
new SystemMessage(systemPrompt),
|
||||
new HumanMessage(state.userMessage),
|
||||
]);
|
||||
const content = typeof response.content === 'string' ? response.content : '';
|
||||
return { messages: [response], response: content };
|
||||
}
|
||||
|
||||
const globalTools = buildGlobalTools();
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const llmWithTools = llm.bindTools!(globalTools);
|
||||
|
||||
const MAX_ITERATIONS = 5;
|
||||
const messageHistory: BaseMessage[] = [
|
||||
new SystemMessage(systemPrompt),
|
||||
new HumanMessage(state.userMessage),
|
||||
];
|
||||
|
||||
for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
|
||||
const response = await llmWithTools.invoke(messageHistory);
|
||||
messageHistory.push(response);
|
||||
|
||||
const toolCalls: ToolCall[] = AIMessage.isInstance(response) ? (response.tool_calls ?? []) : [];
|
||||
|
||||
console.log(`[Orchestrator] generalAgent loop iteration=${iteration}: tool_calls=[${toolCalls.map((c) => c.name).join(', ')}], content="${String(typeof response.content === 'string' ? response.content : '').slice(0, 100)}"`);
|
||||
|
||||
if (toolCalls.length === 0) {
|
||||
const content = typeof response.content === 'string' ? response.content : '';
|
||||
return { messages: messageHistory, response: content };
|
||||
}
|
||||
|
||||
for (const toolCall of toolCalls) {
|
||||
const matched = globalTools.find((t) => t.name === toolCall.name);
|
||||
if (!matched) {
|
||||
messageHistory.push(
|
||||
new ToolMessage({
|
||||
content: `Error: tool "${toolCall.name}" is not available.`,
|
||||
tool_call_id: toolCall.id ?? crypto.randomUUID(),
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const output = await matched.invoke({ ...toolCall, type: 'tool_call' as const });
|
||||
messageHistory.push(
|
||||
new ToolMessage({
|
||||
content: typeof output === 'string' ? output : JSON.stringify(output),
|
||||
tool_call_id: toolCall.id ?? crypto.randomUUID(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const lastAiMsg = [...messageHistory].reverse().find((m) => AIMessage.isInstance(m));
|
||||
const fallbackContent = lastAiMsg && typeof lastAiMsg.content === 'string' ? lastAiMsg.content : '';
|
||||
return { messages: messageHistory, response: fallbackContent };
|
||||
}
|
||||
|
||||
/** Routing function: reads state.route and returns the next node name */
|
||||
function routeDecision(state: State): string {
|
||||
switch (state.route) {
|
||||
case 'project': return 'projectAgent';
|
||||
case 'knowledge': return 'knowledgeAgent';
|
||||
case 'general': return 'generalAgent';
|
||||
default: return 'generalAgent';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Compile the graph (singleton, reused across calls)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildGraph() {
|
||||
return new StateGraph(OrchestratorState)
|
||||
.addNode('classifyIntent', classifyIntent)
|
||||
.addNode('projectAgent', projectAgent)
|
||||
.addNode('knowledgeAgent', knowledgeAgent)
|
||||
.addNode('generalAgent', generalAgent)
|
||||
.addEdge(START, 'classifyIntent')
|
||||
.addConditionalEdges('classifyIntent', routeDecision, [
|
||||
'projectAgent', 'knowledgeAgent', 'generalAgent',
|
||||
])
|
||||
.addEdge('projectAgent', END)
|
||||
.addEdge('knowledgeAgent', END)
|
||||
.addEdge('generalAgent', END)
|
||||
.compile();
|
||||
}
|
||||
|
||||
let compiledGraph: ReturnType<typeof buildGraph> | null = null;
|
||||
|
||||
function getGraph() {
|
||||
if (!compiledGraph) {
|
||||
compiledGraph = buildGraph();
|
||||
}
|
||||
return compiledGraph;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Streaming helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function sendStreamChunk(sender: Electron.WebContents | undefined, token: string, done: boolean): void {
|
||||
if (!sender || sender.isDestroyed()) return;
|
||||
sender.send(AI_STREAM_CHANNEL, { token, done });
|
||||
}
|
||||
|
||||
function sendAction(sender: Electron.WebContents | undefined, action: { type: string; taskId?: string; count?: number }): void {
|
||||
if (!sender || sender.isDestroyed()) return;
|
||||
sender.send(AI_ACTION_CHANNEL, action);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Orchestrate (public entry point)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function orchestrate(input: OrchestrateInput): Promise<OrchestrateResult> {
|
||||
const { message, context, sender } = input;
|
||||
currentSender = sender;
|
||||
|
||||
// Quick check: is an LLM available?
|
||||
const llm = await getLLM();
|
||||
if (!llm) {
|
||||
return { response: '', error: 'AI provider not configured. Please add your token in Settings.' };
|
||||
}
|
||||
|
||||
try {
|
||||
const graph = getGraph();
|
||||
|
||||
// Use streaming to push tokens to the renderer in real-time
|
||||
const stream = await graph.stream(
|
||||
{
|
||||
userMessage: message,
|
||||
chatContext: context,
|
||||
route: 'general' as const,
|
||||
response: '',
|
||||
},
|
||||
{ streamMode: 'messages' as const },
|
||||
);
|
||||
|
||||
let fullResponse = '';
|
||||
|
||||
// Filter state: suppress <tool_call>...</tool_call> blocks that the SDK model emits
|
||||
// as raw text when it attempts to use its built-in tools (sql, bash, etc.) in a
|
||||
// non-tool session. We only want plain-text responses.
|
||||
let inToolCallBlock = false;
|
||||
let toolCallBuffer = '';
|
||||
|
||||
for await (const [chunk, metadata] of stream) {
|
||||
// Only stream tokens from the specialist agent nodes (not the classifier),
|
||||
// and only AI message chunks (not system/human/tool messages that are also
|
||||
// emitted by LangGraph when messageHistory is returned in the state update).
|
||||
if (
|
||||
metadata.langgraph_node !== 'classifyIntent' &&
|
||||
chunk.content &&
|
||||
typeof chunk.content === 'string' &&
|
||||
chunk._getType() === 'ai'
|
||||
) {
|
||||
const text = chunk.content as string;
|
||||
fullResponse += text;
|
||||
|
||||
if (inToolCallBlock) {
|
||||
toolCallBuffer += text;
|
||||
if (toolCallBuffer.includes('</tool_call>')) {
|
||||
const after = toolCallBuffer.split('</tool_call>').slice(1).join('</tool_call>');
|
||||
inToolCallBlock = false;
|
||||
toolCallBuffer = '';
|
||||
const afterClean = after.replace(/^\n/, '');
|
||||
if (afterClean) sendStreamChunk(sender, afterClean, false);
|
||||
}
|
||||
} else if (text.includes('<tool_call>')) {
|
||||
const before = text.split('<tool_call>')[0];
|
||||
if (before) sendStreamChunk(sender, before, false);
|
||||
inToolCallBlock = true;
|
||||
toolCallBuffer = '<tool_call>' + text.split('<tool_call>').slice(1).join('<tool_call>');
|
||||
if (toolCallBuffer.includes('</tool_call>')) {
|
||||
const after = toolCallBuffer.split('</tool_call>').slice(1).join('</tool_call>');
|
||||
inToolCallBlock = false;
|
||||
toolCallBuffer = '';
|
||||
const afterClean = after.replace(/^\n/, '');
|
||||
if (afterClean) sendStreamChunk(sender, afterClean, false);
|
||||
}
|
||||
} else {
|
||||
sendStreamChunk(sender, text, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Signal stream completion
|
||||
sendStreamChunk(sender, '', true);
|
||||
|
||||
return { response: fullResponse };
|
||||
} catch (err) {
|
||||
sendStreamChunk(sender, '', true);
|
||||
|
||||
const errMsg = err instanceof Error ? err.message : String(err);
|
||||
|
||||
if (errMsg.includes('401') || errMsg.includes('403') || errMsg.includes('auth') || errMsg.includes('Unauthorized')) {
|
||||
return { response: '', error: 'Authentication failed. Please check your token in Settings.' };
|
||||
}
|
||||
if (errMsg.includes('timeout') || errMsg.includes('Timeout')) {
|
||||
return { response: '', error: 'Request timed out. Please try again.' };
|
||||
}
|
||||
if (errMsg.toLowerCase().includes('list models') || errMsg.toLowerCase().includes('listmodels')) {
|
||||
return { response: '', error: 'GitHub Copilot model service is unavailable. Please re-authenticate (copilot auth login) or switch to a different AI provider in Settings.' };
|
||||
}
|
||||
|
||||
return { response: '', error: errMsg };
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Daily Brief (dedicated entry point)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const DAILY_BRIEF_PROMPT =
|
||||
`Act as a professional and efficient executive assistant. Give me a concise daily brief for today.
|
||||
|
||||
Strict Rules:
|
||||
- Adopt a polite, formal, and helpful tone. Do not use emojis, slang, or overly casual encouragement.
|
||||
- Focus strictly on actionable or critical items: tasks due today, upcoming deadlines this week, overdue items, and significant project activity.
|
||||
- Do NOT mention zero-counts (e.g., "no overdue items") or general statistics (e.g., "2 active projects", "2 completed tasks"). Only report what needs my attention.
|
||||
- Do NOT include any headers, titles, dates, or greetings.
|
||||
- Do NOT use labels like "Due today:" or "Overdue:". Integrate the information naturally into sentences.
|
||||
- Use **bold** for key phrases, task names, or project names.
|
||||
- Keep the entire response to 3-5 sentences.`;
|
||||
|
||||
export async function dailyBrief(sender?: Electron.WebContents): Promise<OrchestrateResult> {
|
||||
return orchestrate({
|
||||
message: DAILY_BRIEF_PROMPT,
|
||||
context: { type: 'global' },
|
||||
sender,
|
||||
});
|
||||
}
|
||||
93
src/main/ai/provider.ts
Normal file
93
src/main/ai/provider.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { getStore } from '../store';
|
||||
import { getToken, setToken as storeToken } from './token';
|
||||
|
||||
export interface AIProvider {
|
||||
/** Internal key, e.g. 'copilot', 'openai', 'anthropic' */
|
||||
name: string;
|
||||
/** Human-readable label shown in Settings UI */
|
||||
displayName: string;
|
||||
/** Initialize with a token. Returns true if the provider is ready. */
|
||||
initialize(token: string): Promise<boolean>;
|
||||
/** Whether the provider is initialized and ready to handle requests. */
|
||||
isReady(): boolean;
|
||||
/** If true, this provider uses external auth (e.g. CLI OAuth) and doesn't need a stored token. */
|
||||
usesExternalAuth?: boolean;
|
||||
}
|
||||
|
||||
const providers = new Map<string, AIProvider>();
|
||||
let activeProvider: AIProvider | null = null;
|
||||
|
||||
/** Register a provider implementation. Call at import time. */
|
||||
export function registerProvider(provider: AIProvider): void {
|
||||
providers.set(provider.name, provider);
|
||||
}
|
||||
|
||||
/** Get the currently active provider (may be null if none configured). */
|
||||
export function getActiveProvider(): AIProvider | null {
|
||||
return activeProvider;
|
||||
}
|
||||
|
||||
/** Get the active provider's name from electron-store. */
|
||||
export function getActiveProviderName(): string {
|
||||
return getStore().get('aiProvider');
|
||||
}
|
||||
|
||||
/** Switch to a different registered provider. */
|
||||
function setActiveProviderName(name: string): void {
|
||||
const provider = providers.get(name);
|
||||
if (!provider) throw new Error(`Unknown AI provider: ${name}`);
|
||||
activeProvider = provider;
|
||||
getStore().set('aiProvider', name);
|
||||
}
|
||||
|
||||
/** Store token for the active provider and re-initialize it. */
|
||||
export async function saveTokenAndInit(token: string): Promise<void> {
|
||||
const name = getActiveProviderName();
|
||||
await storeToken(name, token);
|
||||
const provider = providers.get(name);
|
||||
if (provider) {
|
||||
await provider.initialize(token);
|
||||
activeProvider = provider;
|
||||
}
|
||||
}
|
||||
|
||||
/** Check whether the active provider has credentials (stored token or external auth). */
|
||||
export async function hasActiveToken(): Promise<boolean> {
|
||||
const name = getActiveProviderName();
|
||||
const provider = providers.get(name);
|
||||
// Providers with external auth (e.g. Copilot CLI OAuth) don't need a stored token
|
||||
if (provider?.usesExternalAuth) return true;
|
||||
const token = await getToken(name);
|
||||
return token !== null && token.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the AI subsystem on app startup.
|
||||
* Reads the active provider from settings, loads its token from keychain,
|
||||
* and calls provider.initialize() if a token exists.
|
||||
*/
|
||||
export async function initAI(): Promise<void> {
|
||||
const name = getActiveProviderName();
|
||||
const provider = providers.get(name);
|
||||
if (!provider) {
|
||||
console.log(`[AI] No provider registered for "${name}"`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Providers with external auth (e.g. Copilot CLI OAuth) initialize without a stored token
|
||||
if (provider.usesExternalAuth) {
|
||||
const ready = await provider.initialize('');
|
||||
activeProvider = provider;
|
||||
console.log(`[AI] Provider "${provider.displayName}" initialized (external auth): ready=${ready}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const token = await getToken(name);
|
||||
if (token) {
|
||||
const ready = await provider.initialize(token);
|
||||
activeProvider = provider;
|
||||
console.log(`[AI] Provider "${provider.displayName}" initialized: ready=${ready}`);
|
||||
} else {
|
||||
console.log(`[AI] No token stored for provider "${provider.displayName}"`);
|
||||
}
|
||||
}
|
||||
71
src/main/ai/token.ts
Normal file
71
src/main/ai/token.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { safeStorage } from 'electron';
|
||||
import { getStore } from '../store';
|
||||
|
||||
/**
|
||||
* Token storage with two-tier fallback:
|
||||
* 1. Electron safeStorage + electron-store (encrypted at rest)
|
||||
* 2. Plain electron-store (last resort — e.g. WSL with no keyring)
|
||||
*/
|
||||
|
||||
function canUseSafeStorage(): boolean {
|
||||
try {
|
||||
return safeStorage.isEncryptionAvailable();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- electron-store helpers (with optional safeStorage encryption) ---
|
||||
|
||||
function readFromStore(providerName: string): string | null {
|
||||
const tokens = getStore().get('encryptedTokens');
|
||||
const stored = tokens[providerName];
|
||||
if (!stored) return null;
|
||||
|
||||
if (canUseSafeStorage()) {
|
||||
try {
|
||||
return safeStorage.decryptString(Buffer.from(stored, 'base64'));
|
||||
} catch {
|
||||
// Stored value might be plaintext from a previous fallback
|
||||
return stored;
|
||||
}
|
||||
}
|
||||
// No encryption available — value is stored as plaintext
|
||||
return stored;
|
||||
}
|
||||
|
||||
function writeToStore(providerName: string, token: string): void {
|
||||
let value: string;
|
||||
if (canUseSafeStorage()) {
|
||||
value = safeStorage.encryptString(token).toString('base64');
|
||||
} else {
|
||||
// Last resort: store plaintext (WSL with no keyring)
|
||||
value = token;
|
||||
}
|
||||
const tokens = getStore().get('encryptedTokens');
|
||||
getStore().set('encryptedTokens', { ...tokens, [providerName]: value });
|
||||
}
|
||||
|
||||
function removeFromStore(providerName: string): void {
|
||||
const tokens = getStore().get('encryptedTokens');
|
||||
const { [providerName]: _, ...rest } = tokens;
|
||||
getStore().set('encryptedTokens', rest);
|
||||
}
|
||||
|
||||
// --- public API ---
|
||||
|
||||
/** Read a stored token for the given provider. */
|
||||
export async function getToken(providerName: string): Promise<string | null> {
|
||||
return readFromStore(providerName);
|
||||
}
|
||||
|
||||
/** Store a token for the given provider. */
|
||||
export async function setToken(providerName: string, token: string): Promise<void> {
|
||||
writeToStore(providerName, token);
|
||||
}
|
||||
|
||||
/** Delete a stored token for the given provider. */
|
||||
async function deleteToken(providerName: string): Promise<boolean> {
|
||||
removeFromStore(providerName);
|
||||
return true;
|
||||
}
|
||||
@@ -32,6 +32,8 @@ const MIGRATION_SQL = `
|
||||
priority TEXT NOT NULL DEFAULT 'medium',
|
||||
assignee TEXT,
|
||||
due_date INTEGER,
|
||||
is_ai_suggested INTEGER NOT NULL DEFAULT 0,
|
||||
is_approved INTEGER NOT NULL DEFAULT 1,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
@@ -53,6 +55,14 @@ const MIGRATION_SQL = `
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS task_comments (
|
||||
id TEXT PRIMARY KEY,
|
||||
task_id TEXT NOT NULL,
|
||||
author TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
`;
|
||||
|
||||
type DbInstance = ReturnType<typeof drizzle<typeof schema>>;
|
||||
@@ -71,6 +81,10 @@ export function initDb(): DbInstance {
|
||||
// Run non-destructive migrations on every start
|
||||
sqlite.exec(MIGRATION_SQL);
|
||||
|
||||
// Additive column migrations (SQLite has no ADD COLUMN IF NOT EXISTS)
|
||||
try { sqlite.exec('ALTER TABLE tasks ADD COLUMN is_ai_suggested INTEGER NOT NULL DEFAULT 0'); } catch { /* already exists */ }
|
||||
try { sqlite.exec('ALTER TABLE tasks ADD COLUMN is_approved INTEGER NOT NULL DEFAULT 1'); } catch { /* already exists */ }
|
||||
|
||||
dbInstance = drizzle(sqlite, { schema });
|
||||
return dbInstance;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ export const tasks = sqliteTable('tasks', {
|
||||
priority: text('priority').notNull().default('medium'),
|
||||
assignee: text('assignee'),
|
||||
dueDate: integer('due_date', { mode: 'number' }),
|
||||
isAiSuggested: integer('is_ai_suggested', { mode: 'number' }).notNull().default(0),
|
||||
isApproved: integer('is_approved', { mode: 'number' }).notNull().default(1),
|
||||
createdAt: integer('created_at', { mode: 'number' }).notNull(),
|
||||
});
|
||||
|
||||
@@ -49,6 +51,14 @@ export const notes = sqliteTable('notes', {
|
||||
updatedAt: integer('updated_at', { mode: 'number' }).notNull(),
|
||||
});
|
||||
|
||||
export const taskComments = sqliteTable('task_comments', {
|
||||
id: text('id').primaryKey(),
|
||||
taskId: text('task_id').notNull(),
|
||||
author: text('author').notNull(),
|
||||
content: text('content').notNull(),
|
||||
createdAt: integer('created_at', { mode: 'number' }).notNull(),
|
||||
});
|
||||
|
||||
// Inferred TypeScript types — no manual duplication
|
||||
export type Client = InferSelectModel<typeof clients>;
|
||||
export type NewClient = InferInsertModel<typeof clients>;
|
||||
@@ -64,3 +74,6 @@ export type NewCheckpoint = InferInsertModel<typeof checkpoints>;
|
||||
|
||||
export type Note = InferSelectModel<typeof notes>;
|
||||
export type NewNote = InferInsertModel<typeof notes>;
|
||||
|
||||
export type TaskComment = InferSelectModel<typeof taskComments>;
|
||||
export type NewTaskComment = InferInsertModel<typeof taskComments>;
|
||||
|
||||
147
src/main/db/vectordb.ts
Normal file
147
src/main/db/vectordb.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import * as lancedb from 'vectordb';
|
||||
import { app } from 'electron';
|
||||
import path from 'node:path';
|
||||
import { getDb } from './index';
|
||||
import { notes } from './schema';
|
||||
import { embedText } from '../ai/embeddings';
|
||||
|
||||
interface NoteRecord {
|
||||
id: string;
|
||||
/** Empty string when the note has no project (Arrow string fields don't cleanly handle null) */
|
||||
projectId: string;
|
||||
content: string;
|
||||
vector: number[];
|
||||
}
|
||||
|
||||
export interface SearchResult {
|
||||
id: string;
|
||||
projectId: string;
|
||||
content: string;
|
||||
_distance: number;
|
||||
}
|
||||
|
||||
let conn: lancedb.Connection | null = null;
|
||||
|
||||
/**
|
||||
* Initialize the LanceDB connection. Must be called before any other
|
||||
* function in this module. Vector data is stored at userData/vectors/.
|
||||
*/
|
||||
export async function initVectorDb(): Promise<void> {
|
||||
const vectorPath = path.join(app.getPath('userData'), 'vectors');
|
||||
conn = await lancedb.connect(vectorPath);
|
||||
console.log('[VectorDB] Connected at:', vectorPath);
|
||||
}
|
||||
|
||||
function getConn(): lancedb.Connection {
|
||||
if (!conn) throw new Error('[VectorDB] Not initialized. Call initVectorDb() first.');
|
||||
return conn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed note content and upsert the record into the LanceDB 'notes' table.
|
||||
*
|
||||
* Upsert strategy: delete-then-add.
|
||||
* table.delete(where) is a no-op when no rows match, so this is safe for
|
||||
* both first-time inserts and subsequent updates.
|
||||
*
|
||||
* On the very first call when the table does not yet exist, createTable
|
||||
* infers the Arrow schema from the initial record.
|
||||
*
|
||||
* Throws on error — callers fire-and-forget via .catch().
|
||||
*/
|
||||
export async function upsertNoteEmbedding(
|
||||
noteId: string,
|
||||
projectId: string | null,
|
||||
content: string,
|
||||
): Promise<void> {
|
||||
const c = getConn();
|
||||
const vector = await embedText(content);
|
||||
|
||||
const record: NoteRecord = {
|
||||
id: noteId,
|
||||
projectId: projectId ?? '',
|
||||
content,
|
||||
vector,
|
||||
};
|
||||
|
||||
const tableNames = await c.tableNames();
|
||||
|
||||
if (!tableNames.includes('notes')) {
|
||||
// First embedding: createTable infers the Arrow schema from this record.
|
||||
// The vector dimension (1536 for text-embedding-3-small) is baked in here.
|
||||
await c.createTable('notes', [record]);
|
||||
console.log('[VectorDB] Created notes table');
|
||||
return;
|
||||
}
|
||||
|
||||
const table = await c.openTable<NoteRecord>('notes');
|
||||
// Note IDs are UUID v4 — only [0-9a-f-] chars, no SQL injection risk.
|
||||
await table.delete(`id = '${noteId}'`);
|
||||
await table.add([record]);
|
||||
}
|
||||
|
||||
/**
|
||||
* On first startup, check if the LanceDB 'notes' table exists.
|
||||
* If not, embed all existing SQLite notes and populate LanceDB.
|
||||
*
|
||||
* Per-note errors are caught and logged; a single failure does not
|
||||
* abort the remaining notes.
|
||||
*/
|
||||
export async function migrateNotesIfNeeded(): Promise<void> {
|
||||
const c = getConn();
|
||||
const tableNames = await c.tableNames();
|
||||
|
||||
if (tableNames.includes('notes')) {
|
||||
console.log('[VectorDB] Notes table exists, skipping migration');
|
||||
return;
|
||||
}
|
||||
|
||||
const allNotes = getDb().select().from(notes).all();
|
||||
|
||||
if (allNotes.length === 0) {
|
||||
console.log('[VectorDB] No existing notes to migrate');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[VectorDB] Migrating ${allNotes.length} notes...`);
|
||||
let successCount = 0;
|
||||
|
||||
for (const note of allNotes) {
|
||||
try {
|
||||
const embeddingText = `${note.title}\n\n${note.content}`;
|
||||
await upsertNoteEmbedding(note.id, note.projectId ?? null, embeddingText);
|
||||
successCount++;
|
||||
} catch (err) {
|
||||
console.error(`[VectorDB] Failed to embed note ${note.id} during migration:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[VectorDB] Migration complete: ${successCount}/${allNotes.length} notes embedded`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed the query string and perform a similarity search across all notes
|
||||
* in the LanceDB 'notes' table. Returns up to `limit` results sorted by
|
||||
* distance (closest first).
|
||||
*
|
||||
* Returns an empty array if the notes table does not exist yet.
|
||||
*/
|
||||
export async function searchNotes(query: string, limit = 5): Promise<SearchResult[]> {
|
||||
const c = getConn();
|
||||
const tableNames = await c.tableNames();
|
||||
|
||||
if (!tableNames.includes('notes')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const queryVector = await embedText(query);
|
||||
const table = await c.openTable('notes');
|
||||
const results = await table.search(queryVector).limit(limit).execute();
|
||||
|
||||
return results.map((r) => ({
|
||||
id: r.id as string,
|
||||
projectId: r.projectId as string,
|
||||
content: r.content as string,
|
||||
_distance: r._distance as number,
|
||||
}));
|
||||
}
|
||||
@@ -4,6 +4,10 @@ import started from 'electron-squirrel-startup';
|
||||
import { initDb } from './db';
|
||||
import { appRouter } from './router';
|
||||
import { createIPCHandler } from './ipc';
|
||||
import { initAI } from './ai/provider';
|
||||
import { initVectorDb, migrateNotesIfNeeded } from './db/vectordb';
|
||||
// Import to trigger provider registration before initAI() runs
|
||||
import './ai/copilot';
|
||||
|
||||
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
|
||||
if (started) {
|
||||
@@ -49,6 +53,12 @@ app.on('ready', () => {
|
||||
initDb();
|
||||
const win = createWindow();
|
||||
createIPCHandler({ router: appRouter, windows: [win] });
|
||||
// AI init is best-effort — never block window creation
|
||||
initAI().catch((err) => console.error('[AI] Init failed:', err));
|
||||
// Vector DB init + migration is best-effort — runs after window is shown
|
||||
initVectorDb()
|
||||
.then(() => migrateNotesIfNeeded())
|
||||
.catch((err) => console.error('[VectorDB] Init or migration failed:', err));
|
||||
});
|
||||
|
||||
// Quit when all windows are closed, except on macOS. There, it's common
|
||||
|
||||
@@ -14,7 +14,13 @@ import {
|
||||
type AnyRouter,
|
||||
} from '@trpc/server';
|
||||
|
||||
export const IPC_CHANNEL = 'trpc';
|
||||
const IPC_CHANNEL = 'trpc';
|
||||
|
||||
/** Context passed to every tRPC procedure via the IPC bridge. */
|
||||
export type TRPCContext = {
|
||||
/** The IPC sender — available for streaming chunks back to the renderer. */
|
||||
sender?: Electron.WebContents;
|
||||
};
|
||||
|
||||
interface IPCRequest {
|
||||
method: 'request';
|
||||
@@ -57,7 +63,7 @@ export function createIPCHandler<TRouter extends AnyRouter>({
|
||||
router,
|
||||
path,
|
||||
getRawInput: async () => rawInput,
|
||||
ctx: {},
|
||||
ctx: { sender: event.sender } satisfies TRPCContext,
|
||||
type,
|
||||
signal: undefined as unknown as AbortSignal,
|
||||
batchIndex: 0,
|
||||
|
||||
@@ -3,10 +3,14 @@ import { z } from 'zod';
|
||||
import { eq, asc, inArray, and, or, like, sql } from 'drizzle-orm';
|
||||
import { alias } from 'drizzle-orm/sqlite-core';
|
||||
import { getDb } from '../db';
|
||||
import { clients, projects, tasks, checkpoints, notes } from '../db/schema';
|
||||
import { clients, projects, tasks, checkpoints, notes, taskComments } from '../db/schema';
|
||||
import { getStore } from '../store';
|
||||
import { saveTokenAndInit, hasActiveToken } from '../ai/provider';
|
||||
import { orchestrate, dailyBrief } from '../ai/orchestrator';
|
||||
import { upsertNoteEmbedding } from '../db/vectordb';
|
||||
import type { TRPCContext } from '../ipc';
|
||||
|
||||
const t = initTRPC.create();
|
||||
const t = initTRPC.context<TRPCContext>().create();
|
||||
|
||||
const router = t.router;
|
||||
const publicProcedure = t.procedure;
|
||||
@@ -199,12 +203,13 @@ const tasksRouter = router({
|
||||
: undefined,
|
||||
);
|
||||
|
||||
const orderByClause =
|
||||
const priorityExpr = sql`CASE ${tasks.priority} WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END`;
|
||||
const orderByClauses =
|
||||
input?.orderBy === 'dueDate'
|
||||
? asc(tasks.dueDate)
|
||||
? [asc(tasks.dueDate), asc(priorityExpr)]
|
||||
: input?.orderBy === 'priority'
|
||||
? asc(sql`CASE ${tasks.priority} WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END`)
|
||||
: asc(tasks.createdAt);
|
||||
? [asc(priorityExpr), asc(tasks.dueDate)]
|
||||
: [asc(tasks.dueDate), asc(priorityExpr)];
|
||||
|
||||
return db
|
||||
.select({
|
||||
@@ -216,6 +221,8 @@ const tasksRouter = router({
|
||||
priority: tasks.priority,
|
||||
assignee: tasks.assignee,
|
||||
dueDate: tasks.dueDate,
|
||||
isAiSuggested: tasks.isAiSuggested,
|
||||
isApproved: tasks.isApproved,
|
||||
createdAt: tasks.createdAt,
|
||||
projectName: projects.name,
|
||||
clientName: sql<string | null>`CASE WHEN ${clients.parentId} IS NOT NULL THEN ${parentClients.name} ELSE ${clients.name} END`,
|
||||
@@ -226,7 +233,7 @@ const tasksRouter = router({
|
||||
.leftJoin(clients, eq(projects.clientId, clients.id))
|
||||
.leftJoin(parentClients, eq(clients.parentId, parentClients.id))
|
||||
.where(conditions)
|
||||
.orderBy(orderByClause)
|
||||
.orderBy(...orderByClauses)
|
||||
.all();
|
||||
}),
|
||||
|
||||
@@ -263,6 +270,8 @@ const tasksRouter = router({
|
||||
assignees: z.array(z.string()).optional(),
|
||||
dueDate: z.number().optional(),
|
||||
projectId: z.string().optional(),
|
||||
isAiSuggested: z.number().optional(),
|
||||
isApproved: z.number().optional(),
|
||||
}))
|
||||
.mutation(({ input }) => {
|
||||
const id = crypto.randomUUID();
|
||||
@@ -276,6 +285,8 @@ const tasksRouter = router({
|
||||
assignee: input.assignees?.length ? JSON.stringify(input.assignees) : null,
|
||||
dueDate: input.dueDate ?? null,
|
||||
projectId: input.projectId ?? null,
|
||||
isAiSuggested: input.isAiSuggested ?? 0,
|
||||
isApproved: input.isApproved ?? 1,
|
||||
createdAt: now,
|
||||
}).run();
|
||||
return { id };
|
||||
@@ -291,6 +302,7 @@ const tasksRouter = router({
|
||||
assignees: z.array(z.string()).optional(),
|
||||
dueDate: z.number().optional(),
|
||||
projectId: z.string().optional(),
|
||||
isApproved: z.number().optional(),
|
||||
}))
|
||||
.mutation(({ input }) => {
|
||||
const set: Partial<{
|
||||
@@ -301,6 +313,7 @@ const tasksRouter = router({
|
||||
assignee: string | null;
|
||||
dueDate: number | null;
|
||||
projectId: string | null;
|
||||
isApproved: number;
|
||||
}> = {};
|
||||
if (input.title !== undefined) set.title = input.title;
|
||||
if (input.description !== undefined) set.description = input.description;
|
||||
@@ -308,6 +321,7 @@ const tasksRouter = router({
|
||||
if (input.priority !== undefined) set.priority = input.priority;
|
||||
if (input.assignees !== undefined) set.assignee = input.assignees.length ? JSON.stringify(input.assignees) : null;
|
||||
if (input.dueDate !== undefined) set.dueDate = input.dueDate;
|
||||
if (input.isApproved !== undefined) set.isApproved = input.isApproved;
|
||||
if (input.projectId !== undefined) set.projectId = input.projectId;
|
||||
if (Object.keys(set).length > 0) {
|
||||
getDb().update(tasks).set(set).where(eq(tasks.id, input.id)).run();
|
||||
@@ -321,6 +335,30 @@ const tasksRouter = router({
|
||||
getDb().delete(tasks).where(eq(tasks.id, input.id)).run();
|
||||
return { success: true as const };
|
||||
}),
|
||||
|
||||
dueToday: publicProcedure.query(() => {
|
||||
const now = new Date();
|
||||
const endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999).getTime();
|
||||
|
||||
return getDb()
|
||||
.select({
|
||||
id: tasks.id,
|
||||
title: tasks.title,
|
||||
priority: tasks.priority,
|
||||
dueDate: tasks.dueDate,
|
||||
projectId: tasks.projectId,
|
||||
})
|
||||
.from(tasks)
|
||||
.where(
|
||||
and(
|
||||
sql`${tasks.dueDate} IS NOT NULL`,
|
||||
sql`${tasks.dueDate} <= ${endOfToday}`,
|
||||
sql`${tasks.status} != 'done'`,
|
||||
)
|
||||
)
|
||||
.orderBy(asc(tasks.dueDate))
|
||||
.all();
|
||||
}),
|
||||
});
|
||||
|
||||
const checkpointsRouter = router({
|
||||
@@ -402,7 +440,7 @@ const notesRouter = router({
|
||||
|
||||
create: publicProcedure
|
||||
.input(z.object({ title: z.string(), content: z.string(), projectId: z.string().optional() }))
|
||||
.mutation(({ input }) => {
|
||||
.mutation(async ({ input }) => {
|
||||
const id = crypto.randomUUID();
|
||||
const now = Date.now();
|
||||
getDb().insert(notes).values({
|
||||
@@ -413,18 +451,37 @@ const notesRouter = router({
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}).run();
|
||||
// Fire-and-forget: embed the note. Errors are logged, never thrown.
|
||||
upsertNoteEmbedding(id, input.projectId ?? null, `${input.title}\n\n${input.content}`)
|
||||
.catch((err) => console.error('[VectorDB] Failed to embed note on create:', err));
|
||||
return { id };
|
||||
}),
|
||||
|
||||
update: publicProcedure
|
||||
.input(z.object({ id: z.string(), title: z.string().optional(), content: z.string().optional() }))
|
||||
.mutation(({ input }) => {
|
||||
.mutation(async ({ input }) => {
|
||||
const set: Partial<{ title: string; content: string; updatedAt: number }> = {};
|
||||
if (input.title !== undefined) set.title = input.title;
|
||||
if (input.content !== undefined) set.content = input.content;
|
||||
// Always update updatedAt
|
||||
set.updatedAt = Date.now();
|
||||
getDb().update(notes).set(set).where(eq(notes.id, input.id)).run();
|
||||
|
||||
// Re-embed if searchable text fields changed.
|
||||
// Re-fetch from SQLite so the embedding reflects the full current note
|
||||
// (the update may have changed only one of title or content).
|
||||
if (input.title !== undefined || input.content !== undefined) {
|
||||
const updated = getDb()
|
||||
.select({ id: notes.id, projectId: notes.projectId, title: notes.title, content: notes.content })
|
||||
.from(notes)
|
||||
.where(eq(notes.id, input.id))
|
||||
.all()[0];
|
||||
if (updated) {
|
||||
upsertNoteEmbedding(updated.id, updated.projectId ?? null, `${updated.title}\n\n${updated.content}`)
|
||||
.catch((err) => console.error('[VectorDB] Failed to embed note on update:', err));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}),
|
||||
|
||||
@@ -436,6 +493,41 @@ const notesRouter = router({
|
||||
}),
|
||||
});
|
||||
|
||||
const taskCommentsRouter = router({
|
||||
list: publicProcedure
|
||||
.input(z.object({ taskId: z.string() }))
|
||||
.query(({ input }) => {
|
||||
return getDb()
|
||||
.select()
|
||||
.from(taskComments)
|
||||
.where(eq(taskComments.taskId, input.taskId))
|
||||
.orderBy(asc(taskComments.createdAt))
|
||||
.all();
|
||||
}),
|
||||
|
||||
create: publicProcedure
|
||||
.input(z.object({ taskId: z.string(), author: z.string(), content: z.string() }))
|
||||
.mutation(({ input }) => {
|
||||
const id = crypto.randomUUID();
|
||||
const now = Date.now();
|
||||
getDb().insert(taskComments).values({
|
||||
id,
|
||||
taskId: input.taskId,
|
||||
author: input.author,
|
||||
content: input.content,
|
||||
createdAt: now,
|
||||
}).run();
|
||||
return { id, taskId: input.taskId, author: input.author, content: input.content, createdAt: now };
|
||||
}),
|
||||
|
||||
delete: publicProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(({ input }) => {
|
||||
getDb().delete(taskComments).where(eq(taskComments.id, input.id)).run();
|
||||
return { success: true as const };
|
||||
}),
|
||||
});
|
||||
|
||||
const settingsRouter = router({
|
||||
getSidebarCollapsed: publicProcedure.query(() => getStore().get('sidebarCollapsed')),
|
||||
setSidebarCollapsed: publicProcedure
|
||||
@@ -444,6 +536,13 @@ const settingsRouter = router({
|
||||
getStore().set('sidebarCollapsed', input.collapsed);
|
||||
return null;
|
||||
}),
|
||||
getUserName: publicProcedure.query(() => getStore().get('userName')),
|
||||
setUserName: publicProcedure
|
||||
.input(z.object({ name: z.string() }))
|
||||
.mutation(({ input }) => {
|
||||
getStore().set('userName', input.name);
|
||||
return null;
|
||||
}),
|
||||
});
|
||||
|
||||
const aiRouter = router({
|
||||
@@ -453,13 +552,39 @@ const aiRouter = router({
|
||||
context: z.object({
|
||||
type: z.enum(['global', 'project']),
|
||||
projectId: z.string().optional(),
|
||||
uiContext: z.string().optional(),
|
||||
}),
|
||||
}))
|
||||
.mutation(() => ({ response: '' })),
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
try {
|
||||
return await orchestrate({
|
||||
message: input.message,
|
||||
context: input.context,
|
||||
sender: ctx.sender,
|
||||
});
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : 'Unknown error';
|
||||
return { response: '', error: msg };
|
||||
}
|
||||
}),
|
||||
setToken: publicProcedure
|
||||
.input(z.object({ token: z.string() }))
|
||||
.mutation(() => null),
|
||||
hasToken: publicProcedure.query(() => false),
|
||||
.mutation(async ({ input }) => {
|
||||
await saveTokenAndInit(input.token);
|
||||
return { success: true };
|
||||
}),
|
||||
dailyBrief: publicProcedure
|
||||
.mutation(async ({ ctx }) => {
|
||||
try {
|
||||
return await dailyBrief(ctx.sender);
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : 'Unknown error';
|
||||
return { response: '', error: msg };
|
||||
}
|
||||
}),
|
||||
hasToken: publicProcedure.query(async () => {
|
||||
return hasActiveToken();
|
||||
}),
|
||||
});
|
||||
|
||||
export const appRouter = router({
|
||||
@@ -470,6 +595,7 @@ export const appRouter = router({
|
||||
tasks: tasksRouter,
|
||||
checkpoints: checkpointsRouter,
|
||||
notes: notesRouter,
|
||||
taskComments: taskCommentsRouter,
|
||||
ai: aiRouter,
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,9 @@ import Store from 'electron-store';
|
||||
|
||||
interface AppSettings {
|
||||
sidebarCollapsed: boolean;
|
||||
aiProvider: string;
|
||||
encryptedTokens: Record<string, string>;
|
||||
userName: string;
|
||||
}
|
||||
|
||||
let _store: Store<AppSettings> | null = null;
|
||||
@@ -11,6 +14,9 @@ export function getStore(): Store<AppSettings> {
|
||||
_store = new Store<AppSettings>({
|
||||
defaults: {
|
||||
sidebarCollapsed: false,
|
||||
aiProvider: 'copilot',
|
||||
encryptedTokens: {},
|
||||
userName: 'there',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,3 +18,26 @@ contextBridge.exposeInMainWorld('electronTRPC', {
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const AI_STREAM_CHANNEL = 'ai:stream';
|
||||
const AI_ACTION_CHANNEL = 'ai:action';
|
||||
|
||||
contextBridge.exposeInMainWorld('electronAI', {
|
||||
/** Subscribe to AI streaming chunks. Returns an unsubscribe function. */
|
||||
onStreamChunk: (cb: (data: { token: string; done: boolean }) => void) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, data: { token: string; done: boolean }) => cb(data);
|
||||
ipcRenderer.on(AI_STREAM_CHANNEL, handler);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(AI_STREAM_CHANNEL, handler);
|
||||
};
|
||||
},
|
||||
|
||||
/** Subscribe to AI action events (task created, suggestions, etc.). Returns unsubscribe. */
|
||||
onAction: (cb: (data: { type: string; taskId?: string; count?: number }) => void) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, data: { type: string; taskId?: string; count?: number }) => cb(data);
|
||||
ipcRenderer.on(AI_ACTION_CHANNEL, handler);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(AI_ACTION_CHANNEL, handler);
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
532
src/renderer/components/ai/AIChatPanel.tsx
Normal file
532
src/renderer/components/ai/AIChatPanel.tsx
Normal file
@@ -0,0 +1,532 @@
|
||||
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
|
||||
import { Sparkles, KeyRound, ArrowUp, ListTodo, TrendingUp, AlertCircle, Lightbulb, ChevronDown, ChevronUp, X } from 'lucide-react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { useAIChat, type ChatContext } from '@/hooks/useAIChat';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { GradualBlur } from '@/components/ui/gradual-blur';
|
||||
|
||||
/** Fluid font size for chat messages — scales with viewport width */
|
||||
const CHAT_FONT = 'clamp(1.125rem, 1.4vw, 1.375rem)';
|
||||
|
||||
const SUGGESTION_CHIPS = [
|
||||
{ icon: ListTodo, label: "What's on my plate today?" },
|
||||
{ icon: TrendingUp, label: 'Summarize this week' },
|
||||
{ icon: AlertCircle, label: 'Any overdue tasks?' },
|
||||
{ icon: Lightbulb, label: 'Suggest next actions' },
|
||||
] as const;
|
||||
|
||||
function getTimeGreeting(): string {
|
||||
const hour = new Date().getHours();
|
||||
if (hour < 12) return 'Good morning,';
|
||||
if (hour < 17) return 'Good afternoon,';
|
||||
return 'Good evening,';
|
||||
}
|
||||
|
||||
/* Entrance animation: staggered fade-up */
|
||||
const stagger = {
|
||||
hidden: {},
|
||||
show: { transition: { staggerChildren: 0.08 } },
|
||||
};
|
||||
|
||||
const fadeUp = {
|
||||
hidden: { opacity: 0, y: 16 },
|
||||
show: {
|
||||
opacity: 1,
|
||||
y: 0,
|
||||
transition: { duration: 0.45, ease: [0.25, 0.1, 0.25, 1] as const },
|
||||
},
|
||||
};
|
||||
|
||||
interface AIChatPanelProps {
|
||||
onOpenSettings?: () => void;
|
||||
isHomePage?: boolean;
|
||||
}
|
||||
|
||||
export function AIChatPanel({
|
||||
onOpenSettings,
|
||||
isHomePage,
|
||||
}: AIChatPanelProps) {
|
||||
const hasTokenQuery = trpc.ai.hasToken.useQuery();
|
||||
|
||||
// Home-specific queries
|
||||
const userNameQuery = trpc.settings.getUserName.useQuery(undefined, { enabled: !!isHomePage });
|
||||
const dueTodayQuery = trpc.tasks.dueToday.useQuery(undefined, { enabled: !!isHomePage });
|
||||
|
||||
const chatContext = useMemo<ChatContext>(
|
||||
() => ({ type: 'global' as const }),
|
||||
[],
|
||||
);
|
||||
const {
|
||||
messages,
|
||||
input,
|
||||
setInput,
|
||||
isStreaming,
|
||||
streamingContent,
|
||||
handleSend: chatHandleSend,
|
||||
} = useAIChat(chatContext);
|
||||
|
||||
// Daily brief state (home page only)
|
||||
const [dailyBrief, setDailyBrief] = useState<string | null>(null);
|
||||
const [briefLoading, setBriefLoading] = useState(false);
|
||||
const briefContentRef = useRef('');
|
||||
const hasFiredBrief = useRef(false);
|
||||
|
||||
const [briefExpanded, setBriefExpanded] = useState(false);
|
||||
const [briefDismissed, setBriefDismissed] = useState(false);
|
||||
|
||||
const messagesContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
// --- Scroll-to-user-message + shrinking placeholder ---
|
||||
const lastUserMsgRef = useRef<HTMLDivElement | null>(null);
|
||||
const [streamingEl, setStreamingEl] = useState<HTMLDivElement | null>(null);
|
||||
const [placeholderHeight, setPlaceholderHeight] = useState<number | null>(null);
|
||||
const initialPlaceholderRef = useRef(0);
|
||||
const pendingScrollRef = useRef(false);
|
||||
|
||||
const briefMutation = trpc.ai.dailyBrief.useMutation();
|
||||
|
||||
// When the user message appears in the list, set the placeholder and scroll it to the top
|
||||
useEffect(() => {
|
||||
if (!pendingScrollRef.current) return;
|
||||
const lastMsg = messages[messages.length - 1];
|
||||
if (!lastMsg || lastMsg.role !== 'user') return;
|
||||
|
||||
pendingScrollRef.current = false;
|
||||
const ph = Math.round(window.innerHeight * 0.71);
|
||||
initialPlaceholderRef.current = ph;
|
||||
setPlaceholderHeight(ph);
|
||||
|
||||
// Double-rAF: wait for the placeholder div to actually paint before scrolling
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
lastUserMsgRef.current?.scrollIntoView({ block: 'start', behavior: 'smooth' });
|
||||
});
|
||||
});
|
||||
}, [messages]);
|
||||
|
||||
// Shrink placeholder in real-time as AI streaming content grows
|
||||
useEffect(() => {
|
||||
if (!isStreaming || !streamingEl) return;
|
||||
const MIN_PADDING = 80;
|
||||
const observer = new ResizeObserver(() => {
|
||||
const contentHeight = streamingEl.getBoundingClientRect().height;
|
||||
setPlaceholderHeight(Math.max(MIN_PADDING, initialPlaceholderRef.current - contentHeight));
|
||||
});
|
||||
observer.observe(streamingEl);
|
||||
return () => observer.disconnect();
|
||||
}, [isStreaming, streamingEl]);
|
||||
|
||||
// Auto-fire daily brief on home page
|
||||
useEffect(() => {
|
||||
if (!isHomePage || hasFiredBrief.current || hasTokenQuery.data !== true) return;
|
||||
hasFiredBrief.current = true;
|
||||
setBriefLoading(true);
|
||||
|
||||
const unsubscribe = window.electronAI.onStreamChunk(({ token, done }) => {
|
||||
if (done) {
|
||||
setDailyBrief(briefContentRef.current);
|
||||
setBriefLoading(false);
|
||||
unsubscribe();
|
||||
return;
|
||||
}
|
||||
briefContentRef.current += token;
|
||||
setDailyBrief(briefContentRef.current);
|
||||
});
|
||||
|
||||
briefMutation.mutate(undefined, {
|
||||
onSuccess: (data) => {
|
||||
if (data.error) {
|
||||
unsubscribe();
|
||||
setDailyBrief(null);
|
||||
setBriefLoading(false);
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
unsubscribe();
|
||||
setDailyBrief(null);
|
||||
setBriefLoading(false);
|
||||
},
|
||||
});
|
||||
}, [isHomePage, hasTokenQuery.data]); // briefMutation excluded — only fire once
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
if (briefLoading) return;
|
||||
pendingScrollRef.current = true;
|
||||
chatHandleSend();
|
||||
}, [briefLoading, chatHandleSend]);
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
};
|
||||
|
||||
const hasMessages = messages.length > 0 || isStreaming;
|
||||
|
||||
// Derived values for home page
|
||||
const dueCount = dueTodayQuery.data?.length ?? 0;
|
||||
const userName = userNameQuery.data ?? 'there';
|
||||
|
||||
return (
|
||||
<div className="absolute inset-0 z-0 flex flex-col bg-background">
|
||||
{/* Sticky brief toast — anchored at top when chatting */}
|
||||
<AnimatePresence>
|
||||
{isHomePage && hasMessages && dailyBrief && !briefDismissed && (
|
||||
<motion.div
|
||||
initial={{ y: -80, opacity: 0 }}
|
||||
animate={{ y: 0, opacity: 1 }}
|
||||
exit={{ y: -80, opacity: 0 }}
|
||||
transition={{ type: 'spring', stiffness: 400, damping: 30 }}
|
||||
className="sticky top-0 z-30 flex justify-center px-4 pt-3 pb-1"
|
||||
>
|
||||
<div className="w-full max-w-2xl rounded-xl border border-border/60 bg-background/80 backdrop-blur-xl shadow-[0_8px_30px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_30px_rgba(0,0,0,0.4)] ring-1 ring-border/10">
|
||||
{/* Toast header — always visible */}
|
||||
<div className="flex items-center gap-2 px-4 py-2.5">
|
||||
<Sparkles size={14} className="text-primary shrink-0" />
|
||||
<span className="text-xs font-semibold tracking-wide text-foreground">Daily Brief</span>
|
||||
<div className="flex-1" />
|
||||
<button
|
||||
onClick={() => setBriefExpanded((v) => !v)}
|
||||
aria-label={briefExpanded ? 'Collapse brief' : 'Expand brief'}
|
||||
className="flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground hover:bg-muted/60"
|
||||
>
|
||||
{briefExpanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setBriefDismissed(true)}
|
||||
aria-label="Dismiss brief"
|
||||
className="flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground hover:bg-muted/60"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
{/* Collapsed: one-line preview */}
|
||||
{!briefExpanded && (
|
||||
<div className="px-4 pb-3 -mt-1">
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{dailyBrief.replace(/[#*_~`>-]/g, '').slice(0, 120)}...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{/* Expanded: full brief content */}
|
||||
<AnimatePresence>
|
||||
{briefExpanded && (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
transition={{ duration: 0.25, ease: [0.25, 0.1, 0.25, 1] }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div className="px-4 pb-3 max-h-64 overflow-y-auto">
|
||||
<ChatMarkdown content={dailyBrief} />
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Scrollable messages area */}
|
||||
<div className="relative flex-1 min-h-0">
|
||||
{/* Gradual blur at the bottom of messages */}
|
||||
{hasMessages && (
|
||||
<GradualBlur
|
||||
position="bottom"
|
||||
strength={0.6}
|
||||
height="4rem"
|
||||
divCount={10}
|
||||
curve="ease-out"
|
||||
opacity={0.8}
|
||||
zIndex={20}
|
||||
/>
|
||||
)}
|
||||
<ScrollArea
|
||||
className="h-full"
|
||||
viewportRef={messagesContainerRef}
|
||||
scrollbarClassName={hasMessages ? 'z-30' : undefined}
|
||||
viewportClassName={
|
||||
isHomePage && !hasMessages
|
||||
? '[&>div]:!flex [&>div]:!flex-col [&>div]:!min-h-full [&>div]:!justify-center'
|
||||
: '[&>div]:!flex [&>div]:!flex-col [&>div]:!min-h-full [&>div]:!justify-end'
|
||||
}
|
||||
>
|
||||
{/* Home page initial state: greeting + brief */}
|
||||
{isHomePage && !hasMessages && (
|
||||
<motion.div
|
||||
className="mx-auto w-full max-w-4xl px-8 pt-14 pb-8"
|
||||
variants={stagger}
|
||||
initial="hidden"
|
||||
animate="show"
|
||||
>
|
||||
<div className="flex flex-col" style={{ gap: 'clamp(2.5rem, 4vh, 4rem)' }}>
|
||||
{/* Greeting — editorial hero moment */}
|
||||
<motion.div variants={fadeUp} className="flex flex-col gap-1">
|
||||
<span
|
||||
className="font-light tracking-wide text-muted-foreground"
|
||||
style={{ fontSize: 'clamp(1rem, 1.6vw, 1.25rem)' }}
|
||||
>
|
||||
{getTimeGreeting()}
|
||||
</span>
|
||||
<h1
|
||||
className="font-bold leading-[1.05]"
|
||||
style={{ fontSize: 'clamp(3.25rem, 5.5vw, 5.5rem)', letterSpacing: '-0.035em' }}
|
||||
>
|
||||
{userName}
|
||||
<span className="text-primary ml-3 inline-block">✦</span>
|
||||
</h1>
|
||||
{dueCount > 0 && (
|
||||
<p
|
||||
className="text-muted-foreground mt-2"
|
||||
style={{ fontSize: 'clamp(0.875rem, 1.2vw, 1.125rem)' }}
|
||||
>
|
||||
<span className="text-foreground font-medium">{dueCount}</span>
|
||||
{' '}task{dueCount !== 1 ? 's' : ''} due today
|
||||
</p>
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
{/* Daily brief */}
|
||||
<motion.div variants={fadeUp} className="max-w-3xl">
|
||||
{hasTokenQuery.data === false ? (
|
||||
<div className="flex flex-col items-start gap-3 py-2">
|
||||
<KeyRound size={20} className="text-muted-foreground" />
|
||||
<p className="text-muted-foreground" style={{ fontSize: 'clamp(0.9375rem, 1.2vw, 1.0625rem)' }}>
|
||||
Configure your AI provider in Settings to enable the daily brief.
|
||||
</p>
|
||||
<Button variant="outline" size="sm" onClick={onOpenSettings}>
|
||||
Open Settings
|
||||
</Button>
|
||||
</div>
|
||||
) : briefLoading && !dailyBrief ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-5 w-3/4" />
|
||||
<Skeleton className="h-5 w-1/2" />
|
||||
<Skeleton className="h-5 w-2/3" />
|
||||
</div>
|
||||
) : dailyBrief ? (
|
||||
<ChatMarkdown content={dailyBrief} size="lg" />
|
||||
) : (
|
||||
<p className="text-muted-foreground" style={{ fontSize: 'clamp(0.9375rem, 1.2vw, 1.0625rem)' }}>
|
||||
Your daily brief will appear here.
|
||||
</p>
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
{/* Input + suggestion links */}
|
||||
<motion.div variants={fadeUp} className="max-w-3xl">
|
||||
<ChatInput
|
||||
input={input}
|
||||
isStreaming={isStreaming || briefLoading}
|
||||
onInputChange={setInput}
|
||||
onKeyDown={handleKeyDown}
|
||||
onSend={handleSend}
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5 mt-5">
|
||||
{SUGGESTION_CHIPS.map((chip) => (
|
||||
<button
|
||||
key={chip.label}
|
||||
type="button"
|
||||
className="group flex items-center gap-3 py-1.5 text-muted-foreground transition-all duration-200 hover:text-foreground hover:translate-x-1 cursor-pointer text-left"
|
||||
style={{ fontSize: 'clamp(0.9375rem, 1.2vw, 1.0625rem)' }}
|
||||
onClick={() => setInput(chip.label)}
|
||||
>
|
||||
<chip.icon
|
||||
size={16}
|
||||
className="shrink-0 transition-colors duration-200 group-hover:text-primary"
|
||||
/>
|
||||
<span>{chip.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Home page with messages: brief stays, then messages */}
|
||||
{isHomePage && hasMessages && (
|
||||
<div className="mx-auto w-full max-w-6xl px-6 pt-8 pb-32">
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Chat messages */}
|
||||
{messages.map((msg, idx) => {
|
||||
const isLastMsg = idx === messages.length - 1;
|
||||
|
||||
if (msg.role === 'user') {
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
ref={isLastMsg ? lastUserMsgRef : undefined}
|
||||
className="flex justify-end"
|
||||
>
|
||||
<div className="ml-auto max-w-[75%] rounded-2xl bg-muted px-4 py-2">
|
||||
<ChatMarkdown content={msg.content} fontSize={CHAT_FONT} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (msg.error) {
|
||||
return (
|
||||
<div key={msg.id} className="mr-auto max-w-[75%]">
|
||||
<p style={{ fontSize: CHAT_FONT }} className="text-destructive whitespace-pre-wrap">
|
||||
{msg.content}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={msg.id} className="mr-auto max-w-[75%]">
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<Sparkles size={16} className="text-foreground" />
|
||||
<span style={{ fontSize: CHAT_FONT }} className="font-semibold">Adiuva</span>
|
||||
</div>
|
||||
<div className="pl-[22px]">
|
||||
<ChatMarkdown content={msg.content} fontSize={CHAT_FONT} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Streaming AI response */}
|
||||
{isStreaming && (
|
||||
<div ref={setStreamingEl} className="mr-auto max-w-[75%]">
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<Sparkles size={16} className="text-foreground" />
|
||||
<span style={{ fontSize: CHAT_FONT }} className="font-semibold">Adiuva</span>
|
||||
</div>
|
||||
{streamingContent ? (
|
||||
<div className="pl-[22px]">
|
||||
<ChatMarkdown content={streamingContent} fontSize={CHAT_FONT} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2 pl-[22px]">
|
||||
<Skeleton className="h-4 w-48" />
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Placeholder: fills viewport after user message, shrinks as AI responds */}
|
||||
{placeholderHeight !== null && (
|
||||
<div
|
||||
aria-hidden
|
||||
style={{
|
||||
height: placeholderHeight,
|
||||
transition: 'height 180ms ease-out',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Non-home messages */}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Fixed input — pinned to the bottom, above the blur */}
|
||||
{hasMessages && (
|
||||
<div className="absolute bottom-0 left-0 right-0 z-30 px-6 pb-5 pt-4 pointer-events-none">
|
||||
<div className="relative pointer-events-auto mx-auto max-w-3xl">
|
||||
<ChatInput
|
||||
input={input}
|
||||
isStreaming={isStreaming || briefLoading}
|
||||
onInputChange={setInput}
|
||||
onKeyDown={handleKeyDown}
|
||||
onSend={handleSend}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- ChatInput: Floating glass card ---------- */
|
||||
|
||||
interface ChatInputProps {
|
||||
input: string;
|
||||
isStreaming: boolean;
|
||||
onInputChange: (value: string) => void;
|
||||
onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
|
||||
onSend: () => void;
|
||||
}
|
||||
|
||||
function ChatInput({
|
||||
input,
|
||||
isStreaming,
|
||||
onInputChange,
|
||||
onKeyDown,
|
||||
onSend,
|
||||
}: ChatInputProps) {
|
||||
return (
|
||||
<div className="relative rounded-2xl bg-background/70 backdrop-blur-xl border border-border/50 shadow-lg ring-1 ring-border/20 transition-shadow focus-within:shadow-xl focus-within:border-ring/50">
|
||||
<div className="flex items-center gap-2 px-4 py-2.5">
|
||||
<textarea
|
||||
value={input}
|
||||
onChange={(e) => onInputChange(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder="Ask me anything..."
|
||||
aria-label="Chat message"
|
||||
rows={1}
|
||||
className="flex-1 resize-none bg-transparent text-sm placeholder:text-muted-foreground outline-none max-h-[7.5rem] overflow-y-auto"
|
||||
style={{ fieldSizing: 'content' } as React.CSSProperties}
|
||||
/>
|
||||
<button
|
||||
onClick={onSend}
|
||||
disabled={!input.trim() || isStreaming}
|
||||
aria-label="Send message"
|
||||
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed disabled:active:scale-100"
|
||||
>
|
||||
<ArrowUp size={16} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- ChatMarkdown: lightweight markdown renderer ---------- */
|
||||
|
||||
export function ChatMarkdown({ content, size = 'sm', fontSize }: { content: string; size?: 'sm' | 'lg'; fontSize?: string }) {
|
||||
return (
|
||||
<div
|
||||
className={`prose dark:prose-invert max-w-none [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 ${size === 'lg' ? 'prose-base' : 'prose-sm'}`}
|
||||
style={fontSize ? { fontSize } : undefined}
|
||||
>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
components={{
|
||||
pre: ({ children }) => (
|
||||
<pre className="bg-muted rounded-lg p-3 overflow-x-auto text-xs">
|
||||
{children}
|
||||
</pre>
|
||||
),
|
||||
code: ({ children, className }) => {
|
||||
if (!className) {
|
||||
return (
|
||||
<code className="bg-muted rounded px-1.5 py-0.5 text-xs font-mono">
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
return <code className={className}>{children}</code>;
|
||||
},
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
389
src/renderer/components/ai/FloatingChat.tsx
Normal file
389
src/renderer/components/ai/FloatingChat.tsx
Normal file
@@ -0,0 +1,389 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { AnimatePresence, motion } from 'framer-motion';
|
||||
import { useNavigate, useRouterState } from '@tanstack/react-router';
|
||||
import { X, ArrowUp } from 'lucide-react';
|
||||
import {
|
||||
useFloatingChat,
|
||||
computeDualAnchor,
|
||||
getChatWidth,
|
||||
CHAT_HEIGHT,
|
||||
PADDING,
|
||||
} from '@/context/FloatingChatContext';
|
||||
import { useAIChat, type ChatContext } from '@/hooks/useAIChat';
|
||||
import { ChatMarkdown } from '@/components/ai/AIChatPanel';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
|
||||
/** Map section IDs to their routes for cross-page navigation */
|
||||
const SECTION_ROUTES: Record<string, string> = {
|
||||
'project-summary': 'project',
|
||||
'project-timeline': 'project',
|
||||
'project-tasks': 'project',
|
||||
'project-notes': 'project',
|
||||
'tasks-overview': '/tasks',
|
||||
'tasks-list': '/tasks',
|
||||
'timeline-chart': '/timeline',
|
||||
'note-editor': 'note',
|
||||
};
|
||||
|
||||
function FloatingChatInner() {
|
||||
const { state, sections, close, setMorphTarget, moveToSection, updatePosition, setPendingSection } = useFloatingChat();
|
||||
const utils = trpc.useUtils();
|
||||
const navigate = useNavigate();
|
||||
const routerState = useRouterState();
|
||||
const prevPathRef = useRef(routerState.location.pathname);
|
||||
|
||||
// Active section lookup
|
||||
const activeSection = sections.get(state.activeSectionId ?? '');
|
||||
|
||||
// Chat context derived from active section
|
||||
const chatContext = useMemo<ChatContext>(
|
||||
() => ({
|
||||
type: activeSection?.projectId ? 'project' : 'global',
|
||||
projectId: activeSection?.projectId,
|
||||
uiContext: activeSection?.label,
|
||||
}),
|
||||
[activeSection?.projectId, activeSection?.label],
|
||||
);
|
||||
|
||||
// Handle [SECTION:xxx] tags from AI responses
|
||||
const handleSectionTag = useCallback((sectionId: string) => {
|
||||
// Same-page: section is already registered
|
||||
const targetSection = sections.get(sectionId);
|
||||
if (targetSection) {
|
||||
moveToSection(sectionId);
|
||||
targetSection.ref.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Cross-page: section not registered, navigate to its route
|
||||
const route = SECTION_ROUTES[sectionId];
|
||||
if (!route) return;
|
||||
|
||||
setPendingSection({ sectionId });
|
||||
|
||||
if (route === 'project' && state.projectId) {
|
||||
// Navigate to the project page (stay on same project)
|
||||
// Project sections re-register on mount and pendingSection will auto-open
|
||||
void navigate({ to: '/projects', search: { projectId: state.projectId } });
|
||||
} else if (route.startsWith('/')) {
|
||||
void navigate({ to: route });
|
||||
}
|
||||
// 'note' type requires noteId — skip cross-page for now
|
||||
}, [sections, moveToSection, setPendingSection, state.projectId, navigate]);
|
||||
|
||||
const {
|
||||
messages,
|
||||
input,
|
||||
setInput,
|
||||
isStreaming,
|
||||
streamingContent,
|
||||
handleSend,
|
||||
clearMessages,
|
||||
} = useAIChat(chatContext, { onSectionTag: handleSectionTag });
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// ---- Close on Escape ----
|
||||
|
||||
useEffect(() => {
|
||||
if (!state.isOpen) return;
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
close();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handler);
|
||||
return () => document.removeEventListener('keydown', handler);
|
||||
}, [state.isOpen, close]);
|
||||
|
||||
// ---- Close on route change (unless cross-page navigation pending) ----
|
||||
|
||||
useEffect(() => {
|
||||
const currentPath = routerState.location.pathname;
|
||||
if (prevPathRef.current !== currentPath && state.isOpen && !state.pendingSection) {
|
||||
close();
|
||||
}
|
||||
prevPathRef.current = currentPath;
|
||||
}, [routerState.location.pathname, state.isOpen, state.pendingSection, close]);
|
||||
|
||||
// ---- Clear messages on close ----
|
||||
|
||||
const prevOpenRef = useRef(state.isOpen);
|
||||
useEffect(() => {
|
||||
if (prevOpenRef.current && !state.isOpen) {
|
||||
clearMessages();
|
||||
}
|
||||
prevOpenRef.current = state.isOpen;
|
||||
}, [state.isOpen, clearMessages]);
|
||||
|
||||
// ---- AI action: morph into newly-created task ----
|
||||
|
||||
useEffect(() => {
|
||||
if (!state.isOpen) return;
|
||||
|
||||
const unsubscribe = window.electronAI.onAction((action) => {
|
||||
if (action.type === 'task_created' && action.taskId) {
|
||||
// Invalidate task queries so the new TaskRow renders
|
||||
void utils.tasks.list.invalidate();
|
||||
|
||||
// Set the morph target layoutId
|
||||
setMorphTarget(`task-morph-${action.taskId}`);
|
||||
|
||||
// Wait for the TaskRow to render, then close (triggering FLIP)
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
close();
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
}, [state.isOpen, utils, setMorphTarget, close]);
|
||||
|
||||
// ---- Window resize: keep within bounds ----
|
||||
|
||||
useEffect(() => {
|
||||
if (!state.isOpen) return;
|
||||
const handler = () => {
|
||||
// Re-anchor if the container would go offscreen
|
||||
const el = containerRef.current;
|
||||
if (el) {
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (rect.right > window.innerWidth || rect.bottom > window.innerHeight) {
|
||||
el.style.left = `${Math.max(PADDING, Math.min(state.position.x, window.innerWidth - getChatWidth() - PADDING))}px`;
|
||||
el.style.top = `${Math.max(PADDING, Math.min(state.position.y, window.innerHeight - CHAT_HEIGHT - PADDING))}px`;
|
||||
}
|
||||
}
|
||||
};
|
||||
window.addEventListener('resize', handler);
|
||||
return () => window.removeEventListener('resize', handler);
|
||||
}, [state.isOpen, state.position.x, state.position.y]);
|
||||
|
||||
// ---- Scroll tracking: dual-anchor repositioning ----
|
||||
|
||||
useEffect(() => {
|
||||
if (!state.isOpen || !state.activeSectionId) return;
|
||||
const section = sections.get(state.activeSectionId);
|
||||
if (!section || section.anchorMode === 'right-margin') return;
|
||||
|
||||
const el = section.ref.current;
|
||||
if (!el) return;
|
||||
|
||||
// Find scrollable ancestor
|
||||
let scrollParent: HTMLElement | null = el.parentElement;
|
||||
while (scrollParent) {
|
||||
const style = getComputedStyle(scrollParent);
|
||||
if (style.overflow === 'auto' || style.overflow === 'scroll' ||
|
||||
style.overflowY === 'auto' || style.overflowY === 'scroll') {
|
||||
break;
|
||||
}
|
||||
// Also check for Radix ScrollArea viewport
|
||||
if (scrollParent.hasAttribute('data-radix-scroll-area-viewport')) break;
|
||||
scrollParent = scrollParent.parentElement;
|
||||
}
|
||||
|
||||
if (!scrollParent) return;
|
||||
|
||||
let rafId: number | null = null;
|
||||
const handleScroll = () => {
|
||||
if (rafId !== null) return;
|
||||
rafId = requestAnimationFrame(() => {
|
||||
rafId = null;
|
||||
const newPos = computeDualAnchor(section);
|
||||
if (newPos) {
|
||||
updatePosition(newPos);
|
||||
}
|
||||
// null = fully off-screen → freeze (do nothing)
|
||||
});
|
||||
};
|
||||
|
||||
scrollParent.addEventListener('scroll', handleScroll, { passive: true });
|
||||
return () => {
|
||||
scrollParent.removeEventListener('scroll', handleScroll);
|
||||
if (rafId !== null) cancelAnimationFrame(rafId);
|
||||
};
|
||||
}, [state.isOpen, state.activeSectionId, sections, updatePosition]);
|
||||
|
||||
// ---- Auto-scroll messages ----
|
||||
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const scrollToBottom = useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (el) el.scrollTo({ top: el.scrollHeight });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
scrollToBottom();
|
||||
}, [messages, streamingContent, scrollToBottom]);
|
||||
|
||||
// ---- Auto-focus input on open ----
|
||||
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
useEffect(() => {
|
||||
if (state.isOpen) {
|
||||
const timer = setTimeout(() => inputRef.current?.focus(), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [state.isOpen]);
|
||||
|
||||
// ---- Input handling ----
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
};
|
||||
|
||||
const hasMessages = messages.length > 0 || isStreaming;
|
||||
|
||||
// Expand the messages panel upward if there's enough space above the input bar,
|
||||
// otherwise expand downward. 320px = 300px max-h + 8px gap + 12px buffer.
|
||||
const expandUp = state.position.y >= 320;
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{state.isOpen && (
|
||||
<motion.div
|
||||
ref={containerRef}
|
||||
key="floating-chat"
|
||||
layout
|
||||
layoutId={state.morphTargetId ?? undefined}
|
||||
initial={{ opacity: 0, scale: 0.95, y: 12 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 12 }}
|
||||
transition={{ type: 'spring', stiffness: 400, damping: 30 }}
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: state.position.x,
|
||||
top: state.position.y,
|
||||
width: state.position.width,
|
||||
zIndex: 9999,
|
||||
}}
|
||||
className="relative"
|
||||
>
|
||||
{/* ---- Messages panel — floats above or below the input bar ---- */}
|
||||
<AnimatePresence>
|
||||
{hasMessages && (
|
||||
<motion.div
|
||||
key="messages-panel"
|
||||
initial={{ opacity: 0, scale: 0.97, y: expandUp ? 8 : -8 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.97, y: expandUp ? 8 : -8 }}
|
||||
transition={{ type: 'spring', stiffness: 400, damping: 30 }}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
width: '100%',
|
||||
...(expandUp
|
||||
? { bottom: 'calc(100% + 8px)' }
|
||||
: { top: 'calc(100% + 8px)' }),
|
||||
}}
|
||||
className="rounded-2xl overflow-hidden"
|
||||
>
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="max-h-[300px] overflow-y-auto rounded-2xl [&::-webkit-scrollbar]:w-2.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border/40"
|
||||
>
|
||||
<div className="flex flex-col gap-2.5 p-3">
|
||||
{messages.map((msg) => {
|
||||
if (msg.role === 'user') {
|
||||
return (
|
||||
<div key={msg.id} className="flex justify-end">
|
||||
<div className="glass-surface-subtle max-w-[80%] rounded-2xl rounded-br-md px-3.5 py-2">
|
||||
<p className="text-xs whitespace-pre-wrap leading-relaxed text-foreground">
|
||||
{msg.content}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (msg.error) {
|
||||
return (
|
||||
<div key={msg.id} className="flex justify-start">
|
||||
<div className="glass-surface-subtle max-w-[80%] rounded-2xl rounded-bl-md px-3.5 py-2 !border-destructive/30">
|
||||
<p className="text-xs text-destructive whitespace-pre-wrap leading-relaxed">
|
||||
{msg.content}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={msg.id} className="flex justify-start">
|
||||
<div className="glass-surface-subtle max-w-[80%] rounded-2xl rounded-bl-md px-3.5 py-2">
|
||||
<div className="text-xs text-foreground">
|
||||
<ChatMarkdown content={msg.content} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Streaming */}
|
||||
{isStreaming && (
|
||||
<div className="flex justify-start">
|
||||
<div className="glass-surface-subtle max-w-[80%] rounded-2xl rounded-bl-md px-3.5 py-2">
|
||||
{streamingContent ? (
|
||||
<div className="text-xs text-foreground">
|
||||
<ChatMarkdown content={streamingContent} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5 py-0.5">
|
||||
<Skeleton className="h-3 w-36" />
|
||||
<Skeleton className="h-3 w-24" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* ---- Floating input bar ---- */}
|
||||
<div className="glass-surface relative rounded-2xl transition-shadow focus-within:shadow-[0_8px_60px_-8px_rgba(0,0,0,0.35)]">
|
||||
{/* Close button */}
|
||||
<button
|
||||
onClick={close}
|
||||
className="absolute -top-1.5 -right-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-muted/90 backdrop-blur-sm border border-border/50 shadow-sm hover:bg-muted transition-colors z-10"
|
||||
>
|
||||
<X size={10} />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-2 px-3 py-2.5">
|
||||
<textarea
|
||||
ref={inputRef}
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={`Ask about ${activeSection?.label ?? 'this section'}...`}
|
||||
rows={1}
|
||||
className="flex-1 resize-none bg-transparent text-sm placeholder:text-muted-foreground/60 outline-none max-h-20 overflow-y-auto"
|
||||
style={{ fieldSizing: 'content' } as React.CSSProperties}
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleSend()}
|
||||
disabled={!input.trim() || isStreaming}
|
||||
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-95 disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
>
|
||||
<ArrowUp size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
|
||||
export function FloatingChatPortal() {
|
||||
return createPortal(<FloatingChatInner />, document.body);
|
||||
}
|
||||
@@ -1,14 +1,22 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, useRouterState } from '@tanstack/react-router';
|
||||
import { LayoutGroup } from 'framer-motion';
|
||||
import {
|
||||
House,
|
||||
ChartGantt,
|
||||
ClipboardCheck,
|
||||
FolderKanban,
|
||||
PanelLeft,
|
||||
ChevronUp,
|
||||
Settings,
|
||||
Sparkles,
|
||||
Check,
|
||||
Sun,
|
||||
Moon,
|
||||
Monitor,
|
||||
Palette
|
||||
} from 'lucide-react';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { useDoubleClickAI } from '@/hooks/useDoubleClickAI';
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
@@ -21,8 +29,33 @@ import {
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarProvider,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
} from '@/components/ui/sidebar';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { AIChatPanel } from '@/components/ai/AIChatPanel';
|
||||
import { FloatingChatPortal } from '@/components/ai/FloatingChat';
|
||||
import { useTheme } from '@/components/theme-provider';
|
||||
import { FloatingChatProvider } from '@/context/FloatingChatContext';
|
||||
|
||||
const NAV_ITEMS = [
|
||||
{ to: '/', icon: House, label: 'Home' },
|
||||
@@ -36,6 +69,16 @@ interface AppShellProps {
|
||||
}
|
||||
|
||||
export function AppShell({ children }: AppShellProps) {
|
||||
return (
|
||||
<FloatingChatProvider>
|
||||
<AppShellInner>{children}</AppShellInner>
|
||||
</FloatingChatProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function AppShellInner({ children }: AppShellProps) {
|
||||
useDoubleClickAI();
|
||||
|
||||
const collapsedQuery = trpc.settings.getSidebarCollapsed.useQuery(undefined, {
|
||||
staleTime: Infinity,
|
||||
});
|
||||
@@ -55,31 +98,105 @@ export function AppShell({ children }: AppShellProps) {
|
||||
setSidebarCollapsedMutation.mutate({ collapsed: !value });
|
||||
};
|
||||
|
||||
return (
|
||||
<SidebarProvider open={open} onOpenChange={handleOpenChange}>
|
||||
<AppSidebar currentPath={currentPath} />
|
||||
<SidebarInset>
|
||||
{children}
|
||||
// AI token dialog state (shared between sidebar gear menu and AIChatPanel prompt)
|
||||
const [tokenDialogOpen, setTokenDialogOpen] = useState(false);
|
||||
const [tokenInput, setTokenInput] = useState('');
|
||||
const [saved, setSaved] = useState(false);
|
||||
const hasTokenQuery = trpc.ai.hasToken.useQuery();
|
||||
const utils = trpc.useUtils();
|
||||
const setTokenMutation = trpc.ai.setToken.useMutation({
|
||||
onSuccess: () => {
|
||||
setSaved(true);
|
||||
setTokenInput('');
|
||||
void utils.ai.hasToken.invalidate();
|
||||
setTimeout(() => setSaved(false), 2000);
|
||||
},
|
||||
});
|
||||
|
||||
{/* Right-edge vertical 'keep scrolling for AI' affordance (non-interactive) */}
|
||||
<div className="absolute right-0 top-0 flex items-end justify-center pt-8 pointer-events-none select-none">
|
||||
<div className="flex flex-col items-center gap-1.5 pr-2">
|
||||
<ChevronUp size={10} className="text-muted-foreground/30" />
|
||||
<span
|
||||
className="text-[9px] text-muted-foreground/30 tracking-widest uppercase font-medium"
|
||||
style={{ writingMode: 'vertical-rl', transform: 'rotate(180deg)' }}
|
||||
>
|
||||
keep scrolling up for AI
|
||||
</span>
|
||||
</div>
|
||||
const isHomePage = currentPath === '/';
|
||||
|
||||
return (
|
||||
<LayoutGroup>
|
||||
<SidebarProvider open={open} onOpenChange={handleOpenChange}>
|
||||
<AppSidebar
|
||||
currentPath={currentPath}
|
||||
setTokenDialogOpen={setTokenDialogOpen}
|
||||
/>
|
||||
<SidebarInset>
|
||||
{isHomePage ? (
|
||||
<AIChatPanel
|
||||
onOpenSettings={() => setTokenDialogOpen(true)}
|
||||
isHomePage
|
||||
/>
|
||||
) : (
|
||||
<div className="relative flex flex-col h-full">
|
||||
<header className="flex items-center gap-2 p-2 md:hidden">
|
||||
<SidebarTrigger />
|
||||
</header>
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
</SidebarInset>
|
||||
</SidebarProvider>
|
||||
|
||||
{/* Floating AI Chat — portal to document.body */}
|
||||
<FloatingChatPortal />
|
||||
|
||||
{/* AI Token Dialog — rendered outside Sidebar to avoid layout conflicts */}
|
||||
<Dialog open={tokenDialogOpen} onOpenChange={(open) => {
|
||||
setTokenDialogOpen(open);
|
||||
if (!open) { setTokenInput(''); setSaved(false); }
|
||||
}}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>AI Provider</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure your AI provider credentials for chat, summaries, and suggestions.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">GitHub Copilot Token</label>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Paste your token here"
|
||||
value={tokenInput}
|
||||
onChange={(e) => setTokenInput(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Your token is stored securely in the OS keychain.
|
||||
{hasTokenQuery.data === true && (
|
||||
<span className="text-green-600 dark:text-green-400 ml-1">A token is currently stored.</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
{saved && (
|
||||
<span className="flex items-center gap-1 text-sm text-green-600 dark:text-green-400 mr-auto">
|
||||
<Check size={14} />
|
||||
Saved
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
disabled={!tokenInput.trim() || setTokenMutation.isPending}
|
||||
onClick={() => setTokenMutation.mutate({ token: tokenInput.trim() })}
|
||||
>
|
||||
{setTokenMutation.isPending ? 'Saving...' : 'Save Token'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</LayoutGroup>
|
||||
);
|
||||
}
|
||||
|
||||
function AppSidebar({ currentPath }: { currentPath: string }) {
|
||||
interface AppSidebarProps {
|
||||
currentPath: string;
|
||||
setTokenDialogOpen: (open: boolean) => void;
|
||||
}
|
||||
|
||||
function AppSidebar({ currentPath, setTokenDialogOpen }: AppSidebarProps) {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
const { theme, setTheme } = useTheme();
|
||||
|
||||
return (
|
||||
<Sidebar collapsible="icon">
|
||||
@@ -143,9 +260,50 @@ function AppSidebar({ currentPath }: { currentPath: string }) {
|
||||
</SidebarGroup>
|
||||
</SidebarContent>
|
||||
|
||||
{/* Collapse toggle — spec: useSidebar() + custom trigger */}
|
||||
{/* Settings gear + Collapse toggle */}
|
||||
<SidebarFooter>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<SidebarMenuButton tooltip="Settings">
|
||||
<Settings />
|
||||
<span>Settings</span>
|
||||
</SidebarMenuButton>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent side="right" align="end" className="w-56">
|
||||
<DropdownMenuItem onSelect={() => setTokenDialogOpen(true)}>
|
||||
<Sparkles className="mr-2 size-4" />
|
||||
AI Provider
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>
|
||||
<Palette className="mr-2 size-4" />
|
||||
<span>Theme</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuSubContent>
|
||||
<DropdownMenuItem onSelect={() => setTheme('light')}>
|
||||
<Sun className="mr-2 size-4" />
|
||||
Light
|
||||
{theme === 'light' && <Check className="ml-auto size-4" />}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => setTheme('dark')}>
|
||||
<Moon className="mr-2 size-4" />
|
||||
Dark
|
||||
{theme === 'dark' && <Check className="ml-auto size-4" />}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => setTheme('system')}>
|
||||
<Monitor className="mr-2 size-4" />
|
||||
System
|
||||
{theme === 'system' && <Check className="ml-auto size-4" />}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenuSub>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton onClick={toggleSidebar} tooltip="Toggle Sidebar">
|
||||
<PanelLeft />
|
||||
@@ -154,6 +312,7 @@ function AppSidebar({ currentPath }: { currentPath: string }) {
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarFooter>
|
||||
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
|
||||
85
src/renderer/components/notes/MilkdownEditor.tsx
Normal file
85
src/renderer/components/notes/MilkdownEditor.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { Crepe, CrepeFeature } from '@milkdown/crepe';
|
||||
import { upload, uploadConfig } from '@milkdown/plugin-upload';
|
||||
|
||||
import '@milkdown/crepe/theme/common/style.css';
|
||||
import '@milkdown/crepe/theme/nord.css';
|
||||
|
||||
function fileToDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result as string);
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
interface MilkdownEditorProps {
|
||||
initialContent: string;
|
||||
onChange: (markdown: string) => void;
|
||||
}
|
||||
|
||||
export function MilkdownEditor({ initialContent, onChange }: MilkdownEditorProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const crepeRef = useRef<Crepe | null>(null);
|
||||
const onChangeRef = useRef(onChange);
|
||||
onChangeRef.current = onChange;
|
||||
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return;
|
||||
|
||||
const crepe = new Crepe({
|
||||
root: containerRef.current,
|
||||
defaultValue: initialContent,
|
||||
featureConfigs: {
|
||||
[CrepeFeature.Placeholder]: {
|
||||
text: 'Start writing...',
|
||||
},
|
||||
[CrepeFeature.ImageBlock]: {
|
||||
onUpload: fileToDataUrl,
|
||||
inlineOnUpload: fileToDataUrl,
|
||||
blockOnUpload: fileToDataUrl,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Add upload plugin to handle Ctrl+V and drag-drop of image files
|
||||
crepe.editor
|
||||
.config((ctx) => {
|
||||
ctx.update(uploadConfig.key, (prev) => ({
|
||||
...prev,
|
||||
uploader: async (files: FileList, schema: import('@milkdown/prose/model').Schema) => {
|
||||
const results: import('@milkdown/prose/model').Node[] = [];
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const file = files.item(i);
|
||||
if (!file?.type.includes('image')) continue;
|
||||
const src = await fileToDataUrl(file);
|
||||
const node = schema.nodes.image?.createAndFill({ src, alt: file.name });
|
||||
if (node) results.push(node);
|
||||
}
|
||||
return results;
|
||||
},
|
||||
enableHtmlFileUploader: true,
|
||||
}));
|
||||
})
|
||||
.use(upload);
|
||||
|
||||
crepe.on((listener) => {
|
||||
listener.markdownUpdated((_ctx, markdown, prevMarkdown) => {
|
||||
if (markdown !== prevMarkdown) {
|
||||
onChangeRef.current(markdown);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
crepe.create();
|
||||
crepeRef.current = crepe;
|
||||
|
||||
return () => {
|
||||
crepe.destroy();
|
||||
crepeRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return <div ref={containerRef} className="milkdown-container" />;
|
||||
}
|
||||
168
src/renderer/components/projects/KanbanBoard.tsx
Normal file
168
src/renderer/components/projects/KanbanBoard.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { DragDropContext, Droppable, Draggable, type DropResult } from '@hello-pangea/dnd';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { useFloatingChat } from '@/context/FloatingChatContext';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { TaskRow, type TaskItem } from '@/components/tasks/TaskRow';
|
||||
import { NewTaskDialog } from '@/components/tasks/NewTaskDialog';
|
||||
import { EditTaskDialog } from '@/components/tasks/EditTaskDialog';
|
||||
import { TaskDetailDialog } from '@/components/tasks/TaskDetailDialog';
|
||||
|
||||
const COLUMNS = [
|
||||
{ id: 'todo', label: 'To Do' },
|
||||
{ id: 'in_progress', label: 'In Progress' },
|
||||
{ id: 'done', label: 'Completed' },
|
||||
] as const;
|
||||
|
||||
type ColumnId = (typeof COLUMNS)[number]['id'];
|
||||
|
||||
type KanbanBoardProps = {
|
||||
projectId: string;
|
||||
newTaskOpen: boolean;
|
||||
onNewTaskOpenChange: (open: boolean) => void;
|
||||
};
|
||||
|
||||
export function KanbanBoard({ projectId, newTaskOpen, onNewTaskOpenChange }: KanbanBoardProps) {
|
||||
const { state: floatingState } = useFloatingChat();
|
||||
const { data: tasksList } = trpc.tasks.list.useQuery({ projectId });
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const updateTask = trpc.tasks.update.useMutation({
|
||||
onSuccess: () => void utils.tasks.list.invalidate(),
|
||||
});
|
||||
|
||||
const deleteTask = trpc.tasks.delete.useMutation({
|
||||
onSuccess: () => void utils.tasks.list.invalidate(),
|
||||
});
|
||||
|
||||
// Edit / view task dialog state
|
||||
const [editTask, setEditTask] = useState<TaskItem | null>(null);
|
||||
const [viewTask, setViewTask] = useState<TaskItem | null>(null);
|
||||
|
||||
// Group tasks by status (exclude unapproved AI suggestions)
|
||||
const columns = useMemo(() => {
|
||||
const tasks = (tasksList ?? []).filter(
|
||||
(t) => !(t.isAiSuggested === 1 && t.isApproved === 0),
|
||||
);
|
||||
const grouped: Record<ColumnId, TaskItem[]> = {
|
||||
todo: [],
|
||||
in_progress: [],
|
||||
done: [],
|
||||
};
|
||||
for (const task of tasks) {
|
||||
const status = (task.status ?? 'todo') as ColumnId;
|
||||
if (status in grouped) {
|
||||
grouped[status].push(task);
|
||||
} else {
|
||||
grouped.todo.push(task);
|
||||
}
|
||||
}
|
||||
return grouped;
|
||||
}, [tasksList]);
|
||||
|
||||
const handleDragEnd = useCallback(
|
||||
(result: DropResult) => {
|
||||
const { destination, source, draggableId } = result;
|
||||
if (!destination) return;
|
||||
if (destination.droppableId === source.droppableId) return;
|
||||
|
||||
updateTask.mutate({
|
||||
id: draggableId,
|
||||
status: destination.droppableId,
|
||||
});
|
||||
},
|
||||
[updateTask],
|
||||
);
|
||||
|
||||
const handleToggle = useCallback(
|
||||
(taskId: string, currentStatus: string | null) => {
|
||||
const nextStatus =
|
||||
currentStatus === 'todo' ? 'in_progress' :
|
||||
currentStatus === 'in_progress' ? 'done' : 'todo';
|
||||
updateTask.mutate({ id: taskId, status: nextStatus });
|
||||
},
|
||||
[updateTask],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<DragDropContext onDragEnd={handleDragEnd}>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{COLUMNS.map((col) => (
|
||||
<div key={col.id} className="flex flex-col gap-3">
|
||||
{/* Column header */}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">{col.label}</span>
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{columns[col.id].length}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Droppable column */}
|
||||
<Droppable droppableId={col.id}>
|
||||
{(provided, snapshot) => (
|
||||
<div
|
||||
ref={provided.innerRef}
|
||||
{...provided.droppableProps}
|
||||
className={`flex flex-col gap-2 min-h-[120px] rounded-md transition-colors ${
|
||||
snapshot.isDraggingOver ? 'bg-muted/50' : 'bg-muted/20'
|
||||
}`}
|
||||
>
|
||||
{columns[col.id].map((task, index) => (
|
||||
<Draggable
|
||||
key={task.id}
|
||||
draggableId={task.id}
|
||||
index={index}
|
||||
>
|
||||
{(dragProvided) => (
|
||||
<div
|
||||
ref={dragProvided.innerRef}
|
||||
{...dragProvided.draggableProps}
|
||||
{...dragProvided.dragHandleProps}
|
||||
>
|
||||
<TaskRow
|
||||
task={task}
|
||||
onToggle={handleToggle}
|
||||
onEdit={setEditTask}
|
||||
onDelete={(id) => deleteTask.mutate({ id })}
|
||||
onClick={setViewTask}
|
||||
hideBreadcrumb
|
||||
layoutId={
|
||||
floatingState.morphTargetId === `task-morph-${task.id}`
|
||||
? floatingState.morphTargetId
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Draggable>
|
||||
))}
|
||||
{provided.placeholder}
|
||||
</div>
|
||||
)}
|
||||
</Droppable>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</DragDropContext>
|
||||
|
||||
<NewTaskDialog
|
||||
open={newTaskOpen}
|
||||
onOpenChange={onNewTaskOpenChange}
|
||||
defaultProjectId={projectId}
|
||||
/>
|
||||
<EditTaskDialog
|
||||
task={editTask}
|
||||
open={!!editTask}
|
||||
onOpenChange={(open) => { if (!open) setEditTask(null); }}
|
||||
/>
|
||||
<TaskDetailDialog
|
||||
task={viewTask}
|
||||
open={!!viewTask}
|
||||
onOpenChange={(open) => { if (!open) setViewTask(null); }}
|
||||
onEdit={(task) => { setViewTask(null); setEditTask(task); }}
|
||||
onDelete={(id) => { deleteTask.mutate({ id }); setViewTask(null); }}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +1,54 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Sparkles, FileText, CheckCircle2, Milestone } from 'lucide-react';
|
||||
import { Fragment, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Sparkles, FileText, CheckCircle2, Milestone, Plus } from 'lucide-react';
|
||||
import { format } from 'date-fns';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Item, ItemMedia, ItemContent, ItemTitle, ItemDescription } from '@/components/ui/item';
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbList,
|
||||
BreadcrumbSeparator,
|
||||
} from '@/components/ui/breadcrumb';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { KanbanBoard } from './KanbanBoard';
|
||||
import { GanttChart, type GanttCheckpoint } from '@/components/timeline/GanttChart';
|
||||
import { AddCheckpointDialog } from '@/components/timeline/AddCheckpointDialog';
|
||||
import { EditCheckpointDialog } from '@/components/timeline/EditCheckpointDialog';
|
||||
import { useFloatingChat } from '@/context/FloatingChatContext';
|
||||
|
||||
type ProjectDetailProps = {
|
||||
projectId: string;
|
||||
};
|
||||
|
||||
export function ProjectDetail({ projectId }: ProjectDetailProps) {
|
||||
const [newTaskOpen, setNewTaskOpen] = useState(false);
|
||||
const [addCheckpointOpen, setAddCheckpointOpen] = useState(false);
|
||||
const [editingCheckpoint, setEditingCheckpoint] = useState<GanttCheckpoint | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
// AI section refs
|
||||
const summaryRef = useRef<HTMLDivElement>(null);
|
||||
const timelineRef = useRef<HTMLDivElement>(null);
|
||||
const tasksRef = useRef<HTMLDivElement>(null);
|
||||
const notesRef = useRef<HTMLDivElement>(null);
|
||||
const { registerSection, unregisterSection } = useFloatingChat();
|
||||
|
||||
useEffect(() => {
|
||||
registerSection({ id: 'project-summary', label: 'Project Summary', ref: summaryRef, projectId });
|
||||
registerSection({ id: 'project-timeline', label: 'Project Timeline', ref: timelineRef, projectId });
|
||||
registerSection({ id: 'project-tasks', label: 'Tasks', ref: tasksRef, projectId });
|
||||
registerSection({ id: 'project-notes', label: 'Notes', ref: notesRef, projectId });
|
||||
return () => {
|
||||
unregisterSection('project-summary');
|
||||
unregisterSection('project-timeline');
|
||||
unregisterSection('project-tasks');
|
||||
unregisterSection('project-notes');
|
||||
};
|
||||
}, [projectId, registerSection, unregisterSection]);
|
||||
const utils = trpc.useUtils();
|
||||
const { data: project, isLoading } = trpc.projects.get.useQuery({ id: projectId });
|
||||
const { data: clientsList } = trpc.clients.list.useQuery();
|
||||
const { data: notesList } = trpc.notes.list.useQuery({ projectId });
|
||||
@@ -51,10 +86,99 @@ export function ProjectDetail({ projectId }: ProjectDetailProps) {
|
||||
return { approved, total: all.length };
|
||||
}, [checkpointsList]);
|
||||
|
||||
const pendingCheckpoints = useMemo(() =>
|
||||
(checkpointsList ?? []).filter((c) => c.isAiSuggested === 1 && c.isApproved === 0),
|
||||
[checkpointsList],
|
||||
);
|
||||
|
||||
const pendingTasks = useMemo(() =>
|
||||
(tasksList ?? []).filter((t) => t.isAiSuggested === 1 && t.isApproved === 0),
|
||||
[tasksList],
|
||||
);
|
||||
|
||||
// Map checkpoints to GanttChart format
|
||||
const ganttCheckpoints: GanttCheckpoint[] = useMemo(() => {
|
||||
return (checkpointsList ?? []).map((c) => ({
|
||||
id: c.id,
|
||||
title: c.title,
|
||||
date: c.date,
|
||||
projectId,
|
||||
isAiSuggested: c.isAiSuggested,
|
||||
isApproved: c.isApproved,
|
||||
}));
|
||||
}, [checkpointsList, projectId]);
|
||||
|
||||
const { ganttStart, ganttEnd } = useMemo(() => {
|
||||
const now = new Date();
|
||||
if (ganttCheckpoints.length === 0) {
|
||||
const start = new Date(now.getFullYear(), now.getMonth() - 1, 1);
|
||||
const end = new Date(now.getFullYear(), now.getMonth() + 3, 0);
|
||||
return { ganttStart: start, ganttEnd: end };
|
||||
}
|
||||
const dates = ganttCheckpoints.map((c) => c.date);
|
||||
const minDate = new Date(Math.min(...dates));
|
||||
const maxDate = new Date(Math.max(...dates));
|
||||
const start = new Date(minDate.getFullYear(), minDate.getMonth() - 1, 1);
|
||||
const end = new Date(maxDate.getFullYear(), maxDate.getMonth() + 2, 0);
|
||||
return { ganttStart: start, ganttEnd: end };
|
||||
}, [ganttCheckpoints]);
|
||||
|
||||
const deleteCheckpoint = trpc.checkpoints.delete.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.checkpoints.list.invalidate({ projectId });
|
||||
},
|
||||
});
|
||||
|
||||
const updateCheckpoint = trpc.checkpoints.update.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.checkpoints.list.invalidate({ projectId });
|
||||
},
|
||||
});
|
||||
|
||||
const updateTask = trpc.tasks.update.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.tasks.list.invalidate({ projectId });
|
||||
},
|
||||
});
|
||||
|
||||
const deleteTask = trpc.tasks.delete.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.tasks.list.invalidate({ projectId });
|
||||
},
|
||||
});
|
||||
|
||||
const suggestCheckpoints = trpc.ai.chat.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.checkpoints.list.invalidate({ projectId });
|
||||
},
|
||||
});
|
||||
|
||||
const suggestTasks = trpc.ai.chat.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.tasks.list.invalidate({ projectId });
|
||||
},
|
||||
});
|
||||
|
||||
const createNote = trpc.notes.create.useMutation({
|
||||
onSuccess: (data) => {
|
||||
void utils.notes.list.invalidate({ projectId });
|
||||
void navigate({ to: '/notes/$noteId', params: { noteId: data.id } });
|
||||
},
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full text-sm text-muted-foreground">
|
||||
Loading project...
|
||||
<div className="p-6 flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-8 w-56" />
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<Skeleton className="h-20 rounded-lg" />
|
||||
<Skeleton className="h-20 rounded-lg" />
|
||||
<Skeleton className="h-20 rounded-lg" />
|
||||
</div>
|
||||
<Skeleton className="h-16 rounded-lg" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -68,81 +192,262 @@ export function ProjectDetail({ projectId }: ProjectDetailProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-4xl mx-auto flex flex-col gap-6">
|
||||
{/* Breadcrumb */}
|
||||
<div className="p-6 flex flex-col gap-6">
|
||||
{/* Breadcrumb + Project Name */}
|
||||
<div className="flex flex-col gap-1">
|
||||
{breadcrumbPath.length > 0 && (
|
||||
<Breadcrumb>
|
||||
<BreadcrumbList>
|
||||
{breadcrumbPath.map((segment, i) => (
|
||||
<BreadcrumbItem key={i}>
|
||||
<Fragment key={i}>
|
||||
{i > 0 && <BreadcrumbSeparator />}
|
||||
<BreadcrumbItem>
|
||||
<span className="text-muted-foreground">{segment}</span>
|
||||
</BreadcrumbItem>
|
||||
</Fragment>
|
||||
))}
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
)}
|
||||
|
||||
{/* Project Name */}
|
||||
<h1 className="text-2xl font-semibold text-foreground">{project.name}</h1>
|
||||
</div>
|
||||
|
||||
{/* Project Summary Section */}
|
||||
<div ref={summaryRef} data-ai-section="project-summary" className="flex flex-col gap-6">
|
||||
{/* Stat Cards */}
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<Card className="py-4">
|
||||
<CardHeader className="pb-0 pt-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Notes</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="text-2xl font-semibold">{notesCount}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Item variant="muted">
|
||||
<ItemMedia variant="icon">
|
||||
<FileText />
|
||||
</ItemMedia>
|
||||
<ItemContent>
|
||||
<ItemTitle>{notesCount}</ItemTitle>
|
||||
<ItemDescription>Notes</ItemDescription>
|
||||
</ItemContent>
|
||||
</Item>
|
||||
|
||||
<Card className="py-4">
|
||||
<CardHeader className="pb-0 pt-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Tasks Complete</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="text-2xl font-semibold">
|
||||
{taskStats.done}/{taskStats.total}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Item variant="muted">
|
||||
<ItemMedia variant="icon">
|
||||
<CheckCircle2 />
|
||||
</ItemMedia>
|
||||
<ItemContent>
|
||||
<ItemTitle>{taskStats.done}/{taskStats.total}</ItemTitle>
|
||||
<ItemDescription>Tasks Complete</ItemDescription>
|
||||
</ItemContent>
|
||||
</Item>
|
||||
|
||||
<Card className="py-4">
|
||||
<CardHeader className="pb-0 pt-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Milestone className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Checkpoints</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="text-2xl font-semibold">
|
||||
{checkpointStats.approved}/{checkpointStats.total}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Item variant="muted">
|
||||
<ItemMedia variant="icon">
|
||||
<Milestone />
|
||||
</ItemMedia>
|
||||
<ItemContent>
|
||||
<ItemTitle>{checkpointStats.approved}/{checkpointStats.total}</ItemTitle>
|
||||
<ItemDescription>Checkpoints</ItemDescription>
|
||||
</ItemContent>
|
||||
</Item>
|
||||
</div>
|
||||
|
||||
{/* AI Project Summary */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle className="text-sm font-medium">AI Project Summary</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<Item variant="outline">
|
||||
<ItemMedia variant="icon">
|
||||
<Sparkles />
|
||||
</ItemMedia>
|
||||
<ItemContent>
|
||||
<ItemTitle>AI Project Summary</ItemTitle>
|
||||
<ItemDescription>
|
||||
{project.aiSummary || 'AI summary will appear here'}
|
||||
</p>
|
||||
</ItemDescription>
|
||||
</ItemContent>
|
||||
</Item>
|
||||
</div>
|
||||
|
||||
{/* Project Timeline */}
|
||||
<div ref={timelineRef} data-ai-section="project-timeline" className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold">Project Timeline</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={suggestCheckpoints.isPending}
|
||||
onClick={() =>
|
||||
suggestCheckpoints.mutate({
|
||||
message: 'Suggest checkpoints for this project based on the notes.',
|
||||
context: { type: 'project', projectId },
|
||||
})
|
||||
}
|
||||
>
|
||||
<Sparkles className="h-4 w-4 mr-1" />
|
||||
{suggestCheckpoints.isPending ? 'Suggesting…' : 'Suggest checkpoints'}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={() => setAddCheckpointOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<GanttChart
|
||||
checkpoints={ganttCheckpoints}
|
||||
startDate={ganttStart}
|
||||
endDate={ganttEnd}
|
||||
onDelete={(id) => deleteCheckpoint.mutate({ id })}
|
||||
onEdit={(cp) => setEditingCheckpoint(cp)}
|
||||
onToggleApproval={(id, current) =>
|
||||
updateCheckpoint.mutate({ id, isApproved: current === 1 ? 0 : 1 })
|
||||
}
|
||||
/>
|
||||
{pendingCheckpoints.length > 0 && (
|
||||
<div className="flex flex-col gap-2">
|
||||
{pendingCheckpoints.map((cp) => (
|
||||
<Card key={cp.id} className="border-dashed py-3">
|
||||
<CardContent className="flex items-center justify-between px-4 py-0">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium">{cp.title}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{format(new Date(cp.date), 'PPP')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={() => updateCheckpoint.mutate({ id: cp.id, isApproved: 1 })}
|
||||
>
|
||||
Approve
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => deleteCheckpoint.mutate({ id: cp.id })}
|
||||
>
|
||||
Reject
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<AddCheckpointDialog
|
||||
open={addCheckpointOpen}
|
||||
onOpenChange={setAddCheckpointOpen}
|
||||
defaultProjectId={projectId}
|
||||
/>
|
||||
<EditCheckpointDialog
|
||||
checkpoint={editingCheckpoint}
|
||||
onOpenChange={(open) => { if (!open) setEditingCheckpoint(null); }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tasks Kanban */}
|
||||
<div ref={tasksRef} data-ai-section="project-tasks" className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold">Tasks</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={suggestTasks.isPending}
|
||||
onClick={() =>
|
||||
suggestTasks.mutate({
|
||||
message: 'Suggest tasks for this project based on the notes.',
|
||||
context: { type: 'project', projectId },
|
||||
})
|
||||
}
|
||||
>
|
||||
<Sparkles className="h-4 w-4 mr-1" />
|
||||
{suggestTasks.isPending ? 'Suggesting…' : 'Suggest tasks'}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={() => setNewTaskOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{pendingTasks.length > 0 && (
|
||||
<div className="flex flex-col gap-2">
|
||||
{pendingTasks.map((t) => (
|
||||
<Card key={t.id} className="border-dashed py-3">
|
||||
<CardContent className="flex items-center justify-between px-4 py-0">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium">{t.title}</span>
|
||||
{t.description && (
|
||||
<span className="text-xs text-muted-foreground line-clamp-1">
|
||||
{t.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={() => updateTask.mutate({ id: t.id, isApproved: 1 })}
|
||||
>
|
||||
Approve
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => deleteTask.mutate({ id: t.id })}
|
||||
>
|
||||
Reject
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<KanbanBoard
|
||||
projectId={projectId}
|
||||
newTaskOpen={newTaskOpen}
|
||||
onNewTaskOpenChange={setNewTaskOpen}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Notes */}
|
||||
<div ref={notesRef} data-ai-section="project-notes" className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold">Notes</h2>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={createNote.isPending}
|
||||
onClick={() =>
|
||||
createNote.mutate({ title: 'Untitled Note', content: '', projectId })
|
||||
}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
{notesList && notesList.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-5">
|
||||
{notesList.map((note) => (
|
||||
<Item
|
||||
key={note.id}
|
||||
variant="muted"
|
||||
className="min-w-[280px] flex-1 cursor-pointer"
|
||||
onClick={() =>
|
||||
void navigate({ to: '/notes/$noteId', params: { noteId: note.id } })
|
||||
}
|
||||
>
|
||||
<ItemMedia variant="icon">
|
||||
<FileText />
|
||||
</ItemMedia>
|
||||
<ItemContent>
|
||||
<ItemTitle>{note.title}</ItemTitle>
|
||||
<ItemDescription>
|
||||
{format(new Date(note.createdAt), 'PPP')}
|
||||
</ItemDescription>
|
||||
</ItemContent>
|
||||
</Item>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">No notes yet.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ import {
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import {
|
||||
Empty,
|
||||
EmptyContent,
|
||||
@@ -321,7 +322,7 @@ export function ProjectSidebar({ selectedProjectId, onSelectProject }: ProjectSi
|
||||
if (editCreatingClient && editNewClientName.trim()) {
|
||||
// Create a new client
|
||||
const result = await createClientMutation.mutateAsync({ name: editNewClientName.trim() });
|
||||
let parentId = result.id;
|
||||
const parentId = result.id;
|
||||
|
||||
if (editCreatingSubClient && editNewSubClientName.trim()) {
|
||||
// Also create a sub-client under the new client
|
||||
@@ -416,7 +417,7 @@ export function ProjectSidebar({ selectedProjectId, onSelectProject }: ProjectSi
|
||||
</div>
|
||||
|
||||
{/* Project tree */}
|
||||
<div className="flex-1 overflow-y-auto py-1 px-1">
|
||||
<ScrollArea className="flex-1 py-1 px-1">
|
||||
{totalProjects === 0 ? (
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
@@ -824,7 +825,7 @@ export function ProjectSidebar({ selectedProjectId, onSelectProject }: ProjectSi
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
{/* Rename project dialog */}
|
||||
<Dialog
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import { TZDate } from 'react-day-picker';
|
||||
import { Calendar as CalendarIcon, X, UserPlus, Check } from 'lucide-react';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -23,9 +24,13 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
|
||||
import { Calendar } from '@/components/ui/calendar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { TaskItem } from './TaskRow';
|
||||
|
||||
const HOURS = Array.from({ length: 24 }, (_, i) => String(i).padStart(2, '0'));
|
||||
const MINUTES = Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0'));
|
||||
|
||||
function parseAssigneesLocal(raw: string | null): string[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
@@ -46,8 +51,10 @@ export function EditTaskDialog({ task, open, onOpenChange }: EditTaskDialogProps
|
||||
const [description, setDescription] = useState('');
|
||||
const [priority, setPriority] = useState('medium');
|
||||
const [status, setStatus] = useState('todo');
|
||||
const [dueDate, setDueDate] = useState<Date | undefined>();
|
||||
const [dueTime, setDueTime] = useState('');
|
||||
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
const [dueDate, setDueDate] = useState<TZDate | undefined>();
|
||||
const [dueHour, setDueHour] = useState('');
|
||||
const [dueMinute, setDueMinute] = useState('');
|
||||
const [projectId, setProjectId] = useState('');
|
||||
const [assignees, setAssignees] = useState<string[]>([]);
|
||||
const [assigneeInput, setAssigneeInput] = useState('');
|
||||
@@ -61,14 +68,14 @@ export function EditTaskDialog({ task, open, onOpenChange }: EditTaskDialogProps
|
||||
setPriority(task.priority ?? 'medium');
|
||||
setStatus(task.status ?? 'todo');
|
||||
if (task.dueDate) {
|
||||
const d = new Date(task.dueDate);
|
||||
const d = new TZDate(task.dueDate, timezone);
|
||||
setDueDate(d);
|
||||
setDueTime(
|
||||
`${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`,
|
||||
);
|
||||
setDueHour(String(d.getHours()).padStart(2, '0'));
|
||||
setDueMinute(String(d.getMinutes()).padStart(2, '0'));
|
||||
} else {
|
||||
setDueDate(undefined);
|
||||
setDueTime('');
|
||||
setDueHour('');
|
||||
setDueMinute('');
|
||||
}
|
||||
setProjectId(task.projectId ?? '');
|
||||
setAssignees(parseAssigneesLocal(task.assignee));
|
||||
@@ -110,14 +117,16 @@ export function EditTaskDialog({ task, open, onOpenChange }: EditTaskDialogProps
|
||||
|
||||
let resolvedDueDate: number | undefined;
|
||||
if (dueDate) {
|
||||
const d = new Date(dueDate);
|
||||
if (dueTime) {
|
||||
const parts = dueTime.split(':');
|
||||
const h = parseInt(parts[0] ?? '0', 10);
|
||||
const m = parseInt(parts[1] ?? '0', 10);
|
||||
d.setHours(h, m, 0, 0);
|
||||
}
|
||||
resolvedDueDate = d.getTime();
|
||||
const h = dueHour !== '' ? parseInt(dueHour, 10) : 0;
|
||||
const m = dueMinute !== '' ? parseInt(dueMinute, 10) : 0;
|
||||
const tzDate = new TZDate(
|
||||
dueDate.getFullYear(),
|
||||
dueDate.getMonth(),
|
||||
dueDate.getDate(),
|
||||
h, m, 0, 0,
|
||||
timezone,
|
||||
);
|
||||
resolvedDueDate = tzDate.getTime();
|
||||
}
|
||||
|
||||
updateTask.mutate({
|
||||
@@ -193,29 +202,62 @@ export function EditTaskDialog({ task, open, onOpenChange }: EditTaskDialogProps
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{dueDate ? format(dueDate, 'PPP') : 'Pick a due date'}
|
||||
{dueDate
|
||||
? `${format(dueDate, 'PPP')}${dueHour !== '' && dueMinute !== '' ? ` ${dueHour}:${dueMinute}` : ''}`
|
||||
: 'Pick a due date'}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={dueDate}
|
||||
onSelect={setDueDate}
|
||||
/>
|
||||
<div className="border-t px-3 py-2">
|
||||
<label className="text-xs text-muted-foreground mb-1 block">Time (optional)</label>
|
||||
<Input
|
||||
type="time"
|
||||
value={dueTime}
|
||||
onChange={(e) => setDueTime(e.target.value)}
|
||||
className="h-8 text-sm"
|
||||
onSelect={(d) => setDueDate(d as TZDate | undefined)}
|
||||
timeZone={timezone}
|
||||
/>
|
||||
<div className="border-t px-3 py-2 flex flex-col gap-2">
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground mb-1 block">Time (optional, 24h)</label>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Select value={dueHour} onValueChange={setDueHour}>
|
||||
<SelectTrigger className="h-8 w-20 text-sm">
|
||||
<SelectValue placeholder="HH" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{HOURS.map((h) => (
|
||||
<SelectItem key={h} value={h}>{h}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span className="text-muted-foreground text-sm">:</span>
|
||||
<Select value={dueMinute} onValueChange={setDueMinute}>
|
||||
<SelectTrigger className="h-8 w-20 text-sm">
|
||||
<SelectValue placeholder="MM" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MINUTES.map((m) => (
|
||||
<SelectItem key={m} value={m}>{m}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{(dueHour !== '' || dueMinute !== '') && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-xs"
|
||||
onClick={() => { setDueHour(''); setDueMinute(''); }}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{dueDate && dueTime && (
|
||||
{dueDate && dueHour !== '' && dueMinute !== '' && (
|
||||
<p className="text-xs text-muted-foreground pl-1">
|
||||
Due: {format(dueDate, 'PPP')} at {dueTime}
|
||||
Due: {format(dueDate, 'PPP')} at {dueHour}:{dueMinute}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -275,7 +317,8 @@ export function EditTaskDialog({ task, open, onOpenChange }: EditTaskDialogProps
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-64 p-2" align="start">
|
||||
{knownAssignees.length > 0 && (
|
||||
<div className="max-h-36 overflow-y-auto flex flex-col gap-0.5 mb-2">
|
||||
<ScrollArea className="max-h-36 mb-2">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{knownAssignees.map((name) => (
|
||||
<Button
|
||||
key={name}
|
||||
@@ -294,6 +337,7 @@ export function EditTaskDialog({ task, open, onOpenChange }: EditTaskDialogProps
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
{knownAssignees.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground px-2 py-1 mb-2">No existing assignees</p>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import { TZDate } from 'react-day-picker';
|
||||
import { Calendar as CalendarIcon, X, UserPlus, Check, Plus } from 'lucide-react';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -23,8 +24,12 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
|
||||
import { Calendar } from '@/components/ui/calendar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const HOURS = Array.from({ length: 24 }, (_, i) => String(i).padStart(2, '0'));
|
||||
const MINUTES = ['00', '05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55'];
|
||||
|
||||
const NO_CLIENT = '__no_client__';
|
||||
|
||||
interface NewTaskDialogProps {
|
||||
@@ -39,8 +44,10 @@ export function NewTaskDialog({ open, onOpenChange, defaultProjectId, defaultSta
|
||||
const [description, setDescription] = useState('');
|
||||
const [priority, setPriority] = useState('medium');
|
||||
const [status, setStatus] = useState(defaultStatus ?? 'todo');
|
||||
const [dueDate, setDueDate] = useState<Date | undefined>();
|
||||
const [dueTime, setDueTime] = useState('');
|
||||
const [dueDate, setDueDate] = useState<TZDate | undefined>();
|
||||
const [dueHour, setDueHour] = useState('');
|
||||
const [dueMinute, setDueMinute] = useState('');
|
||||
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
const [projectId, setProjectId] = useState(defaultProjectId ?? '');
|
||||
|
||||
// Multi-assignee state
|
||||
@@ -95,7 +102,8 @@ export function NewTaskDialog({ open, onOpenChange, defaultProjectId, defaultSta
|
||||
setPriority('medium');
|
||||
setStatus(defaultStatus ?? 'todo');
|
||||
setDueDate(undefined);
|
||||
setDueTime('');
|
||||
setDueHour('');
|
||||
setDueMinute('');
|
||||
setProjectId(defaultProjectId ?? '');
|
||||
setAssignees([]);
|
||||
setAssigneeInput('');
|
||||
@@ -170,17 +178,19 @@ export function NewTaskDialog({ open, onOpenChange, defaultProjectId, defaultSta
|
||||
e.preventDefault();
|
||||
if (!title.trim()) return;
|
||||
|
||||
// Resolve dueDate + optional time
|
||||
// Resolve dueDate + optional time in the selected timezone
|
||||
let resolvedDueDate: number | undefined;
|
||||
if (dueDate) {
|
||||
const d = new Date(dueDate);
|
||||
if (dueTime) {
|
||||
const parts = dueTime.split(':');
|
||||
const h = parseInt(parts[0] ?? '0', 10);
|
||||
const m = parseInt(parts[1] ?? '0', 10);
|
||||
d.setHours(h, m, 0, 0);
|
||||
}
|
||||
resolvedDueDate = d.getTime();
|
||||
const h = dueHour !== '' ? parseInt(dueHour, 10) : 0;
|
||||
const m = dueMinute !== '' ? parseInt(dueMinute, 10) : 0;
|
||||
const tzDate = new TZDate(
|
||||
dueDate.getFullYear(),
|
||||
dueDate.getMonth(),
|
||||
dueDate.getDate(),
|
||||
h, m, 0, 0,
|
||||
timezone,
|
||||
);
|
||||
resolvedDueDate = tzDate.getTime();
|
||||
}
|
||||
|
||||
// If creating a new project inline, do that first
|
||||
@@ -267,7 +277,7 @@ export function NewTaskDialog({ open, onOpenChange, defaultProjectId, defaultSta
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{dueDate
|
||||
? format(dueDate, dueTime ? 'PPP' : 'PPP')
|
||||
? `${format(dueDate, 'PPP')}${dueHour !== '' && dueMinute !== '' ? ` ${dueHour}:${dueMinute}` : ''}`
|
||||
: 'Pick a due date'}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
@@ -275,22 +285,54 @@ export function NewTaskDialog({ open, onOpenChange, defaultProjectId, defaultSta
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={dueDate}
|
||||
onSelect={setDueDate}
|
||||
/>
|
||||
<div className="border-t px-3 py-2">
|
||||
<label className="text-xs text-muted-foreground mb-1 block">Time (optional)</label>
|
||||
<Input
|
||||
type="time"
|
||||
value={dueTime}
|
||||
onChange={(e) => setDueTime(e.target.value)}
|
||||
className="h-8 text-sm"
|
||||
onSelect={(d) => setDueDate(d as TZDate | undefined)}
|
||||
timeZone={timezone}
|
||||
/>
|
||||
<div className="border-t px-3 py-2 flex flex-col gap-2">
|
||||
{/* Time row */}
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground mb-1 block">Time (optional, 24h)</label>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Select value={dueHour} onValueChange={setDueHour}>
|
||||
<SelectTrigger className="h-8 w-20 text-sm">
|
||||
<SelectValue placeholder="HH" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{HOURS.map((h) => (
|
||||
<SelectItem key={h} value={h}>{h}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span className="text-muted-foreground text-sm">:</span>
|
||||
<Select value={dueMinute} onValueChange={setDueMinute}>
|
||||
<SelectTrigger className="h-8 w-20 text-sm">
|
||||
<SelectValue placeholder="MM" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MINUTES.map((m) => (
|
||||
<SelectItem key={m} value={m}>{m}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{(dueHour !== '' || dueMinute !== '') && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-xs"
|
||||
onClick={() => { setDueHour(''); setDueMinute(''); }}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{dueDate && dueTime && (
|
||||
{dueDate && dueHour !== '' && dueMinute !== '' && (
|
||||
<p className="text-xs text-muted-foreground pl-1">
|
||||
Due: {format(dueDate, 'PPP')} at {dueTime}
|
||||
Due: {format(dueDate, 'PPP')} at {dueHour}:{dueMinute}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -512,7 +554,8 @@ export function NewTaskDialog({ open, onOpenChange, defaultProjectId, defaultSta
|
||||
<PopoverContent className="w-64 p-2" align="start">
|
||||
{/* Known assignees list */}
|
||||
{knownAssignees.length > 0 && (
|
||||
<div className="max-h-36 overflow-y-auto flex flex-col gap-0.5 mb-2">
|
||||
<ScrollArea className="max-h-36 mb-2">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{knownAssignees.map((name) => (
|
||||
<Button
|
||||
key={name}
|
||||
@@ -531,6 +574,7 @@ export function NewTaskDialog({ open, onOpenChange, defaultProjectId, defaultSta
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
{knownAssignees.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground px-2 py-1 mb-2">No existing assignees</p>
|
||||
|
||||
@@ -4,21 +4,21 @@ export function PriorityBadge({ priority }: { priority: string | null }) {
|
||||
switch (priority) {
|
||||
case 'high':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-xs">
|
||||
<span className="inline-flex items-center gap-1 text-xs text-red-600 dark:text-red-400">
|
||||
<ArrowUp className="h-3 w-3" />
|
||||
High
|
||||
</span>
|
||||
);
|
||||
case 'medium':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-xs">
|
||||
<span className="inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400">
|
||||
<ArrowRight className="h-3 w-3" />
|
||||
Medium
|
||||
</span>
|
||||
);
|
||||
case 'low':
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-xs">
|
||||
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<ArrowDown className="h-3 w-3" />
|
||||
Low
|
||||
</span>
|
||||
|
||||
281
src/renderer/components/tasks/TaskDetailDialog.tsx
Normal file
281
src/renderer/components/tasks/TaskDetailDialog.tsx
Normal file
@@ -0,0 +1,281 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Calendar,
|
||||
User,
|
||||
CircleDot,
|
||||
FolderOpen,
|
||||
Zap,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Send,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { PriorityBadge } from './PriorityBadge';
|
||||
import { parseAssignees, type TaskItem } from './TaskRow';
|
||||
|
||||
function formatDate(timestamp: number): string {
|
||||
const d = new Date(timestamp);
|
||||
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
const date = `${months[d.getMonth()]} ${String(d.getDate()).padStart(2, '0')}, ${d.getFullYear()}`;
|
||||
if (d.getHours() === 0 && d.getMinutes() === 0) return date;
|
||||
const h = String(d.getHours()).padStart(2, '0');
|
||||
const m = String(d.getMinutes()).padStart(2, '0');
|
||||
return `${date} ${h}:${m}`;
|
||||
}
|
||||
|
||||
function relativeTime(timestamp: number): string {
|
||||
const diff = Date.now() - timestamp;
|
||||
const minutes = Math.floor(diff / 60000);
|
||||
if (minutes < 1) return 'just now';
|
||||
if (minutes < 60) return `${minutes} min ago`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return `${hours} hr ago`;
|
||||
const days = Math.floor(hours / 24);
|
||||
return `${days}d ago`;
|
||||
}
|
||||
|
||||
const STATUS_CONFIG: Record<string, { label: string; className: string }> = {
|
||||
todo: { label: 'To Do', className: 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300' },
|
||||
in_progress: { label: 'In Progress', className: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' },
|
||||
done: { label: 'Done', className: 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300' },
|
||||
};
|
||||
|
||||
function AuthorAvatar({ name }: { name: string }) {
|
||||
const initials = name
|
||||
.split(/\s+/)
|
||||
.slice(0, 2)
|
||||
.map((w) => w[0]?.toUpperCase() ?? '')
|
||||
.join('');
|
||||
return (
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium">
|
||||
{initials}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface TaskDetailDialogProps {
|
||||
task: TaskItem | null;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onEdit: (task: TaskItem) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
export function TaskDetailDialog({ task, open, onOpenChange, onEdit, onDelete }: TaskDetailDialogProps) {
|
||||
const [commentText, setCommentText] = useState('');
|
||||
const [activeTab, setActiveTab] = useState('description');
|
||||
|
||||
const { data: comments } = trpc.taskComments.list.useQuery(
|
||||
{ taskId: task?.id ?? '' },
|
||||
{ enabled: !!task },
|
||||
);
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const addComment = trpc.taskComments.create.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.taskComments.list.invalidate({ taskId: task?.id ?? '' });
|
||||
setCommentText('');
|
||||
},
|
||||
});
|
||||
|
||||
const deleteComment = trpc.taskComments.delete.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.taskComments.list.invalidate({ taskId: task?.id ?? '' });
|
||||
},
|
||||
});
|
||||
|
||||
if (!task) return null;
|
||||
|
||||
const assignees = parseAssignees(task.assignee);
|
||||
const statusConf = STATUS_CONFIG[task.status ?? 'todo'] ?? { label: 'To Do', className: 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300' };
|
||||
const breadcrumb = [task.clientName, task.subClientName, task.projectName].filter(Boolean);
|
||||
|
||||
const handleAddComment = () => {
|
||||
const text = commentText.trim();
|
||||
if (!text) return;
|
||||
addComment.mutate({ taskId: task.id, author: 'Me', content: text });
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[620px] gap-0 p-0" aria-describedby={undefined}>
|
||||
{/* Header */}
|
||||
<DialogHeader className="px-6 pt-6 pb-4">
|
||||
<DialogTitle className="text-lg font-semibold leading-tight">{task.title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Field rows */}
|
||||
<div className="grid grid-cols-[120px_1fr] gap-y-3 px-6 py-4 text-sm">
|
||||
{/* Assignee */}
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<User className="h-4 w-4" />
|
||||
Assignee
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{assignees.length > 0 ? (
|
||||
assignees.map((name) => (
|
||||
<Badge key={name} variant="secondary" className="text-xs">
|
||||
{name}
|
||||
</Badge>
|
||||
))
|
||||
) : (
|
||||
<span className="text-muted-foreground">Unassigned</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status */}
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<CircleDot className="h-4 w-4" />
|
||||
Status
|
||||
</div>
|
||||
<div>
|
||||
<span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${statusConf.className}`}>
|
||||
{statusConf.label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Due date */}
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<Calendar className="h-4 w-4" />
|
||||
Due date
|
||||
</div>
|
||||
<div>
|
||||
{task.dueDate ? formatDate(task.dueDate) : <span className="text-muted-foreground">No due date</span>}
|
||||
</div>
|
||||
|
||||
{/* Priority */}
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<Zap className="h-4 w-4" />
|
||||
Priority
|
||||
</div>
|
||||
<div>
|
||||
<PriorityBadge priority={task.priority} />
|
||||
</div>
|
||||
|
||||
{/* Project */}
|
||||
{breadcrumb.length > 0 && (
|
||||
<>
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<FolderOpen className="h-4 w-4" />
|
||||
Project
|
||||
</div>
|
||||
<div className="text-sm">{breadcrumb.join(' > ')}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Tabs: Description / Comment */}
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="flex flex-col">
|
||||
<TabsList className="mx-6 mt-3 w-fit">
|
||||
<TabsTrigger value="description">Description</TabsTrigger>
|
||||
<TabsTrigger value="comment">Comment</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="description" className="px-6 py-4 min-h-[120px]">
|
||||
{task.description ? (
|
||||
<p className="text-sm whitespace-pre-wrap">{task.description}</p>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground italic">No description provided.</p>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="comment" className="px-6 py-4 min-h-[120px] flex flex-col gap-4">
|
||||
{/* Comment list */}
|
||||
<ScrollArea className="max-h-[260px]">
|
||||
<div className="flex flex-col gap-4">
|
||||
{(!comments || comments.length === 0) ? (
|
||||
<p className="text-sm text-muted-foreground italic">No comments yet.</p>
|
||||
) : (
|
||||
comments.map((c) => (
|
||||
<div key={c.id} className="flex gap-3">
|
||||
<AuthorAvatar name={c.author} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-sm font-medium">{c.author}</span>
|
||||
<span className="text-xs text-muted-foreground">{relativeTime(c.createdAt)}</span>
|
||||
</div>
|
||||
<div className="rounded-lg bg-muted px-3 py-2 text-sm">
|
||||
{c.content}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-1">
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground hover:text-destructive"
|
||||
onClick={() => deleteComment.mutate({ id: c.id })}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
{/* Add comment input */}
|
||||
<form
|
||||
className="flex items-center gap-2 mt-auto"
|
||||
onSubmit={(e) => { e.preventDefault(); handleAddComment(); }}
|
||||
>
|
||||
<AuthorAvatar name="Me" />
|
||||
<Input
|
||||
placeholder="Add a comment..."
|
||||
value={commentText}
|
||||
onChange={(e) => setCommentText(e.target.value)}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
disabled={!commentText.trim() || addComment.isPending}
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
</Button>
|
||||
</form>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Footer */}
|
||||
<DialogFooter className="px-6 py-4">
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => { onDelete(task.id); onOpenChange(false); }}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-1" />
|
||||
Delete
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => { onEdit(task); onOpenChange(false); }}
|
||||
>
|
||||
<Pencil className="h-4 w-4 mr-1" />
|
||||
Edit
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import { Fragment } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { Calendar, User, Pencil, Trash2 } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
@@ -24,6 +27,8 @@ export type TaskItem = {
|
||||
priority: string | null;
|
||||
assignee: string | null;
|
||||
dueDate: number | null;
|
||||
isAiSuggested: number;
|
||||
isApproved: number;
|
||||
projectName: string | null;
|
||||
clientName: string | null;
|
||||
subClientName: string | null;
|
||||
@@ -41,7 +46,11 @@ export function parseAssignees(raw: string | null): string[] {
|
||||
function formatDueDate(timestamp: number): string {
|
||||
const d = new Date(timestamp);
|
||||
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
return `Due ${months[d.getMonth()]} ${d.getDate()}`;
|
||||
const date = `Due ${months[d.getMonth()]} ${d.getDate()}`;
|
||||
if (d.getHours() === 0 && d.getMinutes() === 0) return date;
|
||||
const h = String(d.getHours()).padStart(2, '0');
|
||||
const m = String(d.getMinutes()).padStart(2, '0');
|
||||
return `${date}, ${h}:${m}`;
|
||||
}
|
||||
|
||||
export function TaskRow({
|
||||
@@ -49,11 +58,17 @@ export function TaskRow({
|
||||
onToggle,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onClick,
|
||||
hideBreadcrumb,
|
||||
layoutId,
|
||||
}: {
|
||||
task: TaskItem;
|
||||
onToggle: (id: string, status: string | null) => void;
|
||||
onEdit?: (task: TaskItem) => void;
|
||||
onDelete?: (id: string) => void;
|
||||
onClick?: (task: TaskItem) => void;
|
||||
hideBreadcrumb?: boolean;
|
||||
layoutId?: string;
|
||||
}) {
|
||||
const isDone = task.status === 'done';
|
||||
|
||||
@@ -62,9 +77,11 @@ export function TaskRow({
|
||||
task.status === 'in_progress' ? 'indeterminate' : false;
|
||||
|
||||
const breadcrumb: string[] = [];
|
||||
if (!hideBreadcrumb) {
|
||||
if (task.clientName) breadcrumb.push(task.clientName);
|
||||
if (task.subClientName) breadcrumb.push(task.subClientName);
|
||||
if (task.projectName) breadcrumb.push(task.projectName);
|
||||
}
|
||||
|
||||
const hasMetadata =
|
||||
task.priority ||
|
||||
@@ -72,23 +89,33 @@ export function TaskRow({
|
||||
breadcrumb.length > 0 ||
|
||||
task.assignee;
|
||||
|
||||
const Wrapper = layoutId ? motion.div : 'div';
|
||||
const wrapperProps = layoutId ? { layoutId, layout: true as const } : {};
|
||||
|
||||
return (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>
|
||||
<div
|
||||
className={`flex flex-col gap-1.5 px-4 py-3 rounded-md border cursor-default select-none ${
|
||||
isDone ? 'bg-green-50 border-green-200' : 'bg-white border-border'
|
||||
}`}
|
||||
<Wrapper
|
||||
{...wrapperProps}
|
||||
className={cn(
|
||||
'flex flex-col gap-1.5 px-4 py-3 rounded-md border select-none transition-colors',
|
||||
isDone
|
||||
? 'bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-900'
|
||||
: 'bg-card border-border',
|
||||
onClick ? 'cursor-pointer hover:bg-accent/50' : 'cursor-default',
|
||||
)}
|
||||
onClick={() => onClick?.(task)}
|
||||
>
|
||||
{/* Row 1: checkbox + title + description */}
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
checked={checkboxState}
|
||||
onCheckedChange={() => onToggle(task.id, task.status)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="mt-0.5 shrink-0"
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className={`text-sm font-semibold ${isDone ? 'line-through text-muted-foreground' : ''}`}>
|
||||
<div className={cn('text-sm font-medium', isDone && 'line-through text-muted-foreground')}>
|
||||
{task.title}
|
||||
</div>
|
||||
{task.description && (
|
||||
@@ -115,10 +142,12 @@ export function TaskRow({
|
||||
<Breadcrumb className="shrink-0">
|
||||
<BreadcrumbList>
|
||||
{breadcrumb.map((part, i) => (
|
||||
<BreadcrumbItem key={i}>
|
||||
<Fragment key={i}>
|
||||
{i > 0 && <BreadcrumbSeparator />}
|
||||
<BreadcrumbItem>
|
||||
<span className="text-xs">{part}</span>
|
||||
</BreadcrumbItem>
|
||||
</Fragment>
|
||||
))}
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
@@ -132,7 +161,7 @@ export function TaskRow({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Wrapper>
|
||||
</ContextMenuTrigger>
|
||||
|
||||
<ContextMenuContent>
|
||||
|
||||
72
src/renderer/components/theme-provider.tsx
Normal file
72
src/renderer/components/theme-provider.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import { createContext, useContext, useEffect, useState } from "react"
|
||||
|
||||
type Theme = "dark" | "light" | "system"
|
||||
|
||||
type ThemeProviderProps = {
|
||||
children: React.ReactNode
|
||||
defaultTheme?: Theme
|
||||
storageKey?: string
|
||||
}
|
||||
|
||||
type ThemeProviderState = {
|
||||
theme: Theme
|
||||
setTheme: (theme: Theme) => void
|
||||
}
|
||||
|
||||
const initialState: ThemeProviderState = {
|
||||
theme: "system",
|
||||
setTheme: () => null,
|
||||
}
|
||||
|
||||
const ThemeProviderContext = createContext<ThemeProviderState>(initialState)
|
||||
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
defaultTheme = "system",
|
||||
storageKey = "adiuva-theme",
|
||||
...props
|
||||
}: ThemeProviderProps) {
|
||||
const [theme, setTheme] = useState<Theme>(
|
||||
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement
|
||||
|
||||
root.classList.remove("light", "dark")
|
||||
|
||||
if (theme === "system") {
|
||||
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
|
||||
.matches
|
||||
? "dark"
|
||||
: "light"
|
||||
root.classList.add(systemTheme)
|
||||
return
|
||||
}
|
||||
|
||||
root.classList.add(theme)
|
||||
}, [theme])
|
||||
|
||||
const value = {
|
||||
theme,
|
||||
setTheme: (theme: Theme) => {
|
||||
localStorage.setItem(storageKey, theme)
|
||||
setTheme(theme)
|
||||
},
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeProviderContext.Provider {...props} value={value}>
|
||||
{children}
|
||||
</ThemeProviderContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const context = useContext(ThemeProviderContext)
|
||||
|
||||
if (context === undefined)
|
||||
throw new Error("useTheme must be used within a ThemeProvider")
|
||||
|
||||
return context
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import { Calendar as CalendarIcon } from 'lucide-react';
|
||||
import { Calendar as CalendarIcon, Check } from 'lucide-react';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from '@/components/ui/select';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Calendar } from '@/components/ui/calendar';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface AddCheckpointDialogProps {
|
||||
@@ -28,10 +29,16 @@ interface AddCheckpointDialogProps {
|
||||
defaultProjectId?: string;
|
||||
}
|
||||
|
||||
interface AddedEntry {
|
||||
title: string;
|
||||
date: Date;
|
||||
}
|
||||
|
||||
export function AddCheckpointDialog({ open, onOpenChange, defaultProjectId }: AddCheckpointDialogProps) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [date, setDate] = useState<Date | undefined>();
|
||||
const [projectId, setProjectId] = useState(defaultProjectId ?? '');
|
||||
const [added, setAdded] = useState<AddedEntry[]>([]);
|
||||
|
||||
const showProjectSelect = !defaultProjectId;
|
||||
const { data: projectsList } = trpc.projects.listAll.useQuery(undefined, {
|
||||
@@ -40,16 +47,19 @@ export function AddCheckpointDialog({ open, onOpenChange, defaultProjectId }: Ad
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const createCheckpoint = trpc.checkpoints.create.useMutation({
|
||||
onSuccess: () => {
|
||||
onSuccess: (_data, variables) => {
|
||||
void utils.checkpoints.list.invalidate();
|
||||
resetAndClose();
|
||||
setAdded((prev) => [...prev, { title: variables.title, date: new Date(variables.date) }]);
|
||||
setTitle('');
|
||||
setDate(undefined);
|
||||
},
|
||||
});
|
||||
|
||||
function resetAndClose() {
|
||||
function handleClose() {
|
||||
setTitle('');
|
||||
setDate(undefined);
|
||||
setProjectId(defaultProjectId ?? '');
|
||||
setAdded([]);
|
||||
onOpenChange(false);
|
||||
}
|
||||
|
||||
@@ -68,11 +78,27 @@ export function AddCheckpointDialog({ open, onOpenChange, defaultProjectId }: Ad
|
||||
const canSubmit = title.trim() && date && (defaultProjectId || projectId);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<Dialog open={open} onOpenChange={(v) => { if (!v) handleClose(); else onOpenChange(v); }}>
|
||||
<DialogContent className="sm:max-w-[400px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Checkpoint</DialogTitle>
|
||||
<DialogTitle>Add Checkpoints</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Just-added list */}
|
||||
{added.length > 0 && (
|
||||
<ScrollArea className="max-h-32">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{added.map((entry, i) => (
|
||||
<div key={i} className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Check className="h-3.5 w-3.5 text-chart-2 shrink-0" />
|
||||
<span className="truncate">{entry.title}</span>
|
||||
<span className="ml-auto text-xs shrink-0">{format(entry.date, 'MMM d')}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<Input
|
||||
placeholder="Checkpoint title"
|
||||
@@ -100,6 +126,7 @@ export function AddCheckpointDialog({ open, onOpenChange, defaultProjectId }: Ad
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={date}
|
||||
numberOfMonths={2}
|
||||
onSelect={setDate}
|
||||
/>
|
||||
</PopoverContent>
|
||||
@@ -121,11 +148,11 @@ export function AddCheckpointDialog({ open, onOpenChange, defaultProjectId }: Ad
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={resetAndClose}>
|
||||
Cancel
|
||||
<Button type="button" variant="outline" onClick={handleClose}>
|
||||
{added.length > 0 ? 'Done' : 'Cancel'}
|
||||
</Button>
|
||||
<Button type="submit" disabled={!canSubmit || createCheckpoint.isPending}>
|
||||
Add Checkpoint
|
||||
{added.length > 0 ? 'Add Another' : 'Add'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
|
||||
107
src/renderer/components/timeline/EditCheckpointDialog.tsx
Normal file
107
src/renderer/components/timeline/EditCheckpointDialog.tsx
Normal file
@@ -0,0 +1,107 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import { Calendar as CalendarIcon } from 'lucide-react';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Calendar } from '@/components/ui/calendar';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { GanttCheckpoint } from './GanttChart';
|
||||
|
||||
interface EditCheckpointDialogProps {
|
||||
checkpoint: GanttCheckpoint | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function EditCheckpointDialog({ checkpoint, onOpenChange }: EditCheckpointDialogProps) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [date, setDate] = useState<Date | undefined>();
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
useEffect(() => {
|
||||
if (checkpoint) {
|
||||
setTitle(checkpoint.title);
|
||||
setDate(new Date(checkpoint.date));
|
||||
}
|
||||
}, [checkpoint]);
|
||||
|
||||
const updateCheckpoint = trpc.checkpoints.update.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.checkpoints.list.invalidate();
|
||||
onOpenChange(false);
|
||||
},
|
||||
});
|
||||
|
||||
function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!checkpoint || !title.trim() || !date) return;
|
||||
|
||||
updateCheckpoint.mutate({
|
||||
id: checkpoint.id,
|
||||
title: title.trim(),
|
||||
date: date.getTime(),
|
||||
});
|
||||
}
|
||||
|
||||
const canSubmit = title.trim() && date;
|
||||
|
||||
return (
|
||||
<Dialog open={!!checkpoint} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[400px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Checkpoint</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<Input
|
||||
placeholder="Checkpoint title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={cn(
|
||||
'justify-start text-left font-normal',
|
||||
!date && 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{date ? format(date, 'PPP') : 'Pick a date'}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={date}
|
||||
onSelect={setDate}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={!canSubmit || updateCheckpoint.isPending}>
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,14 @@
|
||||
import { useRef, useState, useEffect, useCallback } from 'react';
|
||||
import { useRef, useEffect, useState, useCallback } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import { Pencil, Trash2 } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuTrigger,
|
||||
} from '@/components/ui/context-menu';
|
||||
|
||||
export interface GanttCheckpoint {
|
||||
id: string;
|
||||
@@ -18,12 +25,15 @@ interface GanttChartProps {
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
onDelete?: (id: string) => void;
|
||||
onEdit?: (checkpoint: GanttCheckpoint) => void;
|
||||
onToggleApproval?: (id: string, currentApproved: number) => void;
|
||||
}
|
||||
|
||||
const HEADER_HEIGHT = 30;
|
||||
const BASELINE_Y = 70;
|
||||
const SVG_HEIGHT = 100;
|
||||
const DOT_RADIUS = 7;
|
||||
const BASELINE_HEIGHT = 8;
|
||||
const SVG_HEIGHT = 110;
|
||||
const DOT_RADIUS = 10;
|
||||
const PADDING_X = 40;
|
||||
|
||||
function getMonthsBetween(start: Date, end: Date): Date[] {
|
||||
@@ -43,7 +53,14 @@ function dateToX(date: Date, start: Date, end: Date, width: number): number {
|
||||
return PADDING_X + ratio * (width - PADDING_X * 2);
|
||||
}
|
||||
|
||||
export function GanttChart({ checkpoints, startDate, endDate, onDelete }: GanttChartProps) {
|
||||
export function GanttChart({
|
||||
checkpoints,
|
||||
startDate,
|
||||
endDate,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onToggleApproval,
|
||||
}: GanttChartProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState(600);
|
||||
|
||||
@@ -63,10 +80,11 @@ export function GanttChart({ checkpoints, startDate, endDate, onDelete }: GanttC
|
||||
|
||||
const months = getMonthsBetween(startDate, endDate);
|
||||
const todayX = dateToX(new Date(), startDate, endDate, width);
|
||||
const todayVisible = todayX >= PADDING_X && todayX <= width - PADDING_X;
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="w-full overflow-hidden">
|
||||
<svg width={width} height={SVG_HEIGHT} className="select-none">
|
||||
<svg width={width} height={SVG_HEIGHT} className="select-none overflow-visible">
|
||||
{/* Month labels */}
|
||||
{months.map((month) => {
|
||||
const x = dateToX(month, startDate, endDate, width);
|
||||
@@ -86,8 +104,8 @@ export function GanttChart({ checkpoints, startDate, endDate, onDelete }: GanttC
|
||||
x1={x}
|
||||
y1={HEADER_HEIGHT}
|
||||
x2={x}
|
||||
y2={BASELINE_Y + 10}
|
||||
stroke="#e5e5e5"
|
||||
y2={BASELINE_Y + 14}
|
||||
stroke="var(--border)"
|
||||
strokeWidth={1}
|
||||
strokeDasharray="4 4"
|
||||
/>
|
||||
@@ -95,41 +113,47 @@ export function GanttChart({ checkpoints, startDate, endDate, onDelete }: GanttC
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Baseline */}
|
||||
<line
|
||||
x1={PADDING_X}
|
||||
y1={BASELINE_Y}
|
||||
x2={width - PADDING_X}
|
||||
y2={BASELINE_Y}
|
||||
stroke="#d4d4d4"
|
||||
strokeWidth={2}
|
||||
{/* Baseline — thick rounded bar */}
|
||||
<rect
|
||||
x={PADDING_X}
|
||||
y={BASELINE_Y - BASELINE_HEIGHT / 2}
|
||||
width={Math.max(0, width - PADDING_X * 2)}
|
||||
height={BASELINE_HEIGHT}
|
||||
rx={BASELINE_HEIGHT / 2}
|
||||
fill="var(--border)"
|
||||
/>
|
||||
|
||||
{/* Today marker */}
|
||||
{todayX >= PADDING_X && todayX <= width - PADDING_X && (
|
||||
<g>
|
||||
{/* Today marker — dashed line */}
|
||||
{todayVisible && (
|
||||
<line
|
||||
x1={todayX}
|
||||
y1={HEADER_HEIGHT}
|
||||
x2={todayX}
|
||||
y2={BASELINE_Y + 10}
|
||||
stroke="#ef4444"
|
||||
y2={BASELINE_Y + 14}
|
||||
stroke="var(--destructive)"
|
||||
strokeWidth={1.5}
|
||||
strokeDasharray="4 2"
|
||||
/>
|
||||
<text
|
||||
x={todayX}
|
||||
y={BASELINE_Y + 22}
|
||||
textAnchor="middle"
|
||||
fill="#ef4444"
|
||||
fontSize={10}
|
||||
fontFamily="Geist, sans-serif"
|
||||
>
|
||||
Today
|
||||
</text>
|
||||
</g>
|
||||
)}
|
||||
|
||||
{/* Checkpoint dots rendered as foreignObject for Popover */}
|
||||
{/* Today marker — Badge label via foreignObject */}
|
||||
{todayVisible && (
|
||||
<foreignObject
|
||||
x={todayX - 30}
|
||||
y={BASELINE_Y + 12}
|
||||
width={60}
|
||||
height={28}
|
||||
className="overflow-visible"
|
||||
>
|
||||
<div className="flex justify-center">
|
||||
<Badge variant="outline" className="text-[10px] px-1.5 py-0 border-destructive text-destructive">
|
||||
Today
|
||||
</Badge>
|
||||
</div>
|
||||
</foreignObject>
|
||||
)}
|
||||
|
||||
{/* Checkpoint dots */}
|
||||
{checkpoints.map((cp) => {
|
||||
const cx = dateToX(new Date(cp.date), startDate, endDate, width);
|
||||
return (
|
||||
@@ -138,6 +162,8 @@ export function GanttChart({ checkpoints, startDate, endDate, onDelete }: GanttC
|
||||
checkpoint={cp}
|
||||
cx={cx}
|
||||
onDelete={onDelete}
|
||||
onEdit={onEdit}
|
||||
onToggleApproval={onToggleApproval}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -146,83 +172,131 @@ export function GanttChart({ checkpoints, startDate, endDate, onDelete }: GanttC
|
||||
);
|
||||
}
|
||||
|
||||
function getStatusLabel(checkpoint: GanttCheckpoint): { text: string; className: string } {
|
||||
if (checkpoint.isApproved === 0) {
|
||||
return { text: 'Pending', className: 'bg-muted text-muted-foreground' };
|
||||
}
|
||||
if (checkpoint.date < Date.now()) {
|
||||
return { text: 'Completed', className: 'bg-chart-2/15 text-chart-2' };
|
||||
}
|
||||
return { text: 'To Do', className: 'bg-primary/10 text-primary' };
|
||||
}
|
||||
|
||||
function CheckpointDot({
|
||||
checkpoint,
|
||||
cx,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onToggleApproval,
|
||||
}: {
|
||||
checkpoint: GanttCheckpoint;
|
||||
cx: number;
|
||||
onDelete?: (id: string) => void;
|
||||
onEdit?: (checkpoint: GanttCheckpoint) => void;
|
||||
onToggleApproval?: (id: string, currentApproved: number) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const hoverTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const handleDelete = useCallback(() => {
|
||||
onDelete?.(checkpoint.id);
|
||||
setOpen(false);
|
||||
}, [onDelete, checkpoint.id]);
|
||||
const handleMouseEnter = useCallback(() => {
|
||||
if (hoverTimeout.current) clearTimeout(hoverTimeout.current);
|
||||
hoverTimeout.current = setTimeout(() => setHovered(true), 200);
|
||||
}, []);
|
||||
|
||||
const handleMouseLeave = useCallback(() => {
|
||||
if (hoverTimeout.current) clearTimeout(hoverTimeout.current);
|
||||
hoverTimeout.current = setTimeout(() => setHovered(false), 150);
|
||||
}, []);
|
||||
|
||||
// Determine dot style
|
||||
// isApproved=0 (pending AI suggestion) → dashed outline
|
||||
// isApproved=1 + date in past → green (#16a34a) = completed
|
||||
// isApproved=1 + date in future → dark (#171717) = todo
|
||||
const isPending = checkpoint.isApproved === 0;
|
||||
const isPast = checkpoint.date < Date.now();
|
||||
const fill = isPending ? 'none' : (isPast ? '#16a34a' : '#171717');
|
||||
const stroke = isPending ? '#737373' : 'none';
|
||||
const fill = isPending ? 'none' : (isPast ? 'var(--chart-2)' : 'var(--primary)');
|
||||
const stroke = isPending ? 'var(--muted-foreground)' : 'none';
|
||||
const strokeDasharray = isPending ? '3 2' : undefined;
|
||||
const status = getStatusLabel(checkpoint);
|
||||
|
||||
return (
|
||||
<foreignObject
|
||||
x={cx - 16}
|
||||
y={BASELINE_Y - 16}
|
||||
width={32}
|
||||
height={32}
|
||||
className="overflow-visible"
|
||||
>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
className="flex items-center justify-center w-full h-full focus:outline-none cursor-pointer"
|
||||
type="button"
|
||||
>
|
||||
<svg width={DOT_RADIUS * 2 + 2} height={DOT_RADIUS * 2 + 2}>
|
||||
const dotSize = DOT_RADIUS * 2 + 2;
|
||||
const hitArea = dotSize + 8;
|
||||
|
||||
const dotSvg = (
|
||||
<svg width={dotSize} height={dotSize} className="shrink-0">
|
||||
<circle
|
||||
cx={DOT_RADIUS + 1}
|
||||
cy={DOT_RADIUS + 1}
|
||||
r={DOT_RADIUS}
|
||||
fill={fill}
|
||||
stroke={stroke || '#171717'}
|
||||
stroke={stroke || 'var(--primary)'}
|
||||
strokeWidth={isPending ? 1.5 : 0}
|
||||
strokeDasharray={strokeDasharray}
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
return (
|
||||
<foreignObject
|
||||
x={cx - hitArea / 2}
|
||||
y={BASELINE_Y - hitArea / 2}
|
||||
width={hitArea}
|
||||
height={hitArea}
|
||||
className="overflow-visible"
|
||||
>
|
||||
<ContextMenu>
|
||||
<Popover open={hovered}>
|
||||
<ContextMenuTrigger asChild>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
className="flex items-center justify-center w-full h-full focus:outline-none cursor-pointer"
|
||||
type="button"
|
||||
onClick={() => onToggleApproval?.(checkpoint.id, checkpoint.isApproved)}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
{dotSvg}
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-60 p-3" side="top">
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="font-semibold text-sm">{checkpoint.title}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{format(new Date(checkpoint.date), 'PPP')}
|
||||
</div>
|
||||
{checkpoint.projectName && (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Project: {checkpoint.projectName}
|
||||
</div>
|
||||
)}
|
||||
{onDelete && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={handleDelete}
|
||||
className="mt-1"
|
||||
</ContextMenuTrigger>
|
||||
|
||||
<PopoverContent
|
||||
className="w-52 p-3 pointer-events-none"
|
||||
side="top"
|
||||
sideOffset={8}
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="font-semibold text-sm leading-snug truncate">
|
||||
{checkpoint.title}
|
||||
</span>
|
||||
<Badge variant="secondary" className={`text-[10px] px-1.5 py-0 shrink-0 ${status.className}`}>
|
||||
{status.text}
|
||||
</Badge>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{format(new Date(checkpoint.date), 'PPP')}
|
||||
</span>
|
||||
{checkpoint.projectName && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{checkpoint.projectName}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onSelect={() => onEdit?.(checkpoint)}>
|
||||
<Pencil className="h-4 w-4 mr-2" />
|
||||
Edit Checkpoint
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem
|
||||
onSelect={() => onDelete?.(checkpoint.id)}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Delete Checkpoint
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
</foreignObject>
|
||||
);
|
||||
}
|
||||
|
||||
109
src/renderer/components/ui/gradual-blur.tsx
Normal file
109
src/renderer/components/ui/gradual-blur.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import { useMemo } from 'react';
|
||||
|
||||
type Position = 'top' | 'bottom';
|
||||
|
||||
interface GradualBlurProps {
|
||||
/** Edge to attach the blur overlay */
|
||||
position?: Position;
|
||||
/** Base blur strength multiplier */
|
||||
strength?: number;
|
||||
/** Overlay height (CSS value) */
|
||||
height?: string;
|
||||
/** Number of stacked blur layers (higher = smoother) */
|
||||
divCount?: number;
|
||||
/** Use exponential progression for stronger end blur */
|
||||
exponential?: boolean;
|
||||
/** Distribution curve: linear | ease-out */
|
||||
curve?: 'linear' | 'ease-out';
|
||||
/** Opacity applied to each blur layer */
|
||||
opacity?: number;
|
||||
/** z-index for the overlay */
|
||||
zIndex?: number;
|
||||
/** Additional class names */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const getGradientDirection = (position: Position) =>
|
||||
position === 'top' ? 'to top' : 'to bottom';
|
||||
|
||||
export function GradualBlur({
|
||||
position = 'top',
|
||||
strength = 2,
|
||||
height = '6rem',
|
||||
divCount = 5,
|
||||
exponential = false,
|
||||
curve = 'linear',
|
||||
opacity = 1,
|
||||
zIndex = 10,
|
||||
className = '',
|
||||
}: GradualBlurProps) {
|
||||
const blurDivs = useMemo(() => {
|
||||
const divs: React.ReactNode[] = [];
|
||||
const increment = 100 / divCount;
|
||||
const direction = getGradientDirection(position);
|
||||
|
||||
const curveFunc = curve === 'ease-out'
|
||||
? (p: number) => 1 - Math.pow(1 - p, 2)
|
||||
: (p: number) => p;
|
||||
|
||||
for (let i = 1; i <= divCount; i++) {
|
||||
let progress = i / divCount;
|
||||
progress = curveFunc(progress);
|
||||
|
||||
let blurValue: number;
|
||||
if (exponential) {
|
||||
blurValue = Math.pow(2, progress * 4) * 0.0625 * strength;
|
||||
} else {
|
||||
blurValue = progress * strength;
|
||||
}
|
||||
|
||||
const p1 = Math.round((increment * i - increment) * 10) / 10;
|
||||
const p2 = Math.round(increment * i * 10) / 10;
|
||||
const p3 = Math.round((increment * i + increment) * 10) / 10;
|
||||
const p4 = Math.round((increment * i + increment * 2) * 10) / 10;
|
||||
|
||||
let gradient = `transparent ${p1}%, black ${p2}%`;
|
||||
if (p3 <= 100) gradient += `, black ${p3}%`;
|
||||
if (p4 <= 100) gradient += `, transparent ${p4}%`;
|
||||
|
||||
const maskImage = `linear-gradient(${direction}, ${gradient})`;
|
||||
|
||||
divs.push(
|
||||
<div
|
||||
key={i}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
maskImage,
|
||||
WebkitMaskImage: maskImage,
|
||||
backdropFilter: `blur(${blurValue.toFixed(3)}rem)`,
|
||||
WebkitBackdropFilter: `blur(${blurValue.toFixed(3)}rem)`,
|
||||
opacity,
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
return divs;
|
||||
}, [position, strength, divCount, exponential, curve, opacity]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={className}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
[position]: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height,
|
||||
pointerEvents: 'none',
|
||||
zIndex,
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
|
||||
{blurDivs}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
67
src/renderer/components/ui/scroll-area.tsx
Normal file
67
src/renderer/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import * as React from "react"
|
||||
import { ScrollArea as ScrollAreaPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
viewportRef,
|
||||
viewportClassName,
|
||||
scrollbarClassName,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root> & {
|
||||
viewportRef?: React.Ref<HTMLDivElement>;
|
||||
viewportClassName?: string;
|
||||
scrollbarClassName?: string;
|
||||
}) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
ref={viewportRef}
|
||||
data-slot="scroll-area-viewport"
|
||||
className={cn(
|
||||
"focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1",
|
||||
viewportClassName
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar className={scrollbarClassName} />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none z-50",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
262
src/renderer/context/FloatingChatContext.tsx
Normal file
262
src/renderer/context/FloatingChatContext.tsx
Normal file
@@ -0,0 +1,262 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useCallback,
|
||||
useState,
|
||||
useRef,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from 'react';
|
||||
|
||||
// ---------- Types ----------
|
||||
|
||||
interface AISection {
|
||||
id: string; // e.g. "project-tasks", "tasks-list", "timeline-chart"
|
||||
label: string; // Human-readable, e.g. "Tasks", "Project Timeline"
|
||||
ref: RefObject<HTMLElement | null>;
|
||||
projectId?: string; // If section is project-scoped
|
||||
anchorMode?: 'top-right' | 'right-margin'; // default: 'top-right'
|
||||
}
|
||||
|
||||
interface SectionOpenOpts {
|
||||
clickY?: number; // For right-margin mode: Y-coordinate of the double-click
|
||||
}
|
||||
|
||||
interface FloatingChatState {
|
||||
isOpen: boolean;
|
||||
activeSectionId: string | null;
|
||||
position: { x: number; y: number; width: number };
|
||||
morphTargetId: string | null;
|
||||
projectId?: string;
|
||||
pendingSection?: { sectionId: string; clickY?: number }; // For cross-page navigation
|
||||
}
|
||||
|
||||
interface FloatingChatContextValue {
|
||||
// State
|
||||
state: FloatingChatState;
|
||||
sections: Map<string, AISection>;
|
||||
|
||||
// Section registry
|
||||
registerSection: (section: AISection) => void;
|
||||
unregisterSection: (id: string) => void;
|
||||
|
||||
// Actions
|
||||
openAtSection: (sectionId: string, opts?: SectionOpenOpts) => void;
|
||||
moveToSection: (sectionId: string, opts?: SectionOpenOpts) => void;
|
||||
close: () => void;
|
||||
setMorphTarget: (id: string | null) => void;
|
||||
updatePosition: (pos: { x: number; y: number; width: number }) => void;
|
||||
setPendingSection: (pending: { sectionId: string; clickY?: number } | undefined) => void;
|
||||
}
|
||||
|
||||
// ---------- Constants ----------
|
||||
|
||||
/** Dynamic chat width: 35% of viewport, clamped between 320px and 520px. */
|
||||
export function getChatWidth(): number {
|
||||
return Math.min(630, Math.max(320, Math.round(window.innerWidth * 0.35)));
|
||||
}
|
||||
|
||||
export const CHAT_HEIGHT = 420;
|
||||
export const PADDING = 16;
|
||||
|
||||
// ---------- Position computation ----------
|
||||
|
||||
function clampPosition(x: number, y: number): { x: number; y: number } {
|
||||
const w = getChatWidth();
|
||||
return {
|
||||
x: Math.max(PADDING, Math.min(x, window.innerWidth - w - PADDING)),
|
||||
y: Math.max(PADDING, Math.min(y, window.innerHeight - CHAT_HEIGHT - PADDING)),
|
||||
};
|
||||
}
|
||||
|
||||
function computeAnchorPosition(
|
||||
section: AISection,
|
||||
opts?: SectionOpenOpts,
|
||||
): { x: number; y: number; width: number } {
|
||||
const el = section.ref.current;
|
||||
const w = getChatWidth();
|
||||
if (!el) return { x: PADDING, y: PADDING, width: w };
|
||||
|
||||
const rect = el.getBoundingClientRect();
|
||||
const mode = section.anchorMode ?? 'top-right';
|
||||
|
||||
if (mode === 'right-margin') {
|
||||
// Position to the right of the section at the click Y-coordinate
|
||||
const rawX = rect.right + PADDING;
|
||||
const rawY = opts?.clickY ?? rect.top + PADDING;
|
||||
const { x, y } = clampPosition(rawX, rawY);
|
||||
return { x, y, width: w };
|
||||
}
|
||||
|
||||
// Default: top-right of section
|
||||
const rawX = rect.right - w - PADDING;
|
||||
const rawY = rect.top + PADDING;
|
||||
const { x, y } = clampPosition(rawX, rawY);
|
||||
return { x, y, width: w };
|
||||
}
|
||||
|
||||
/**
|
||||
* Dual-anchor recomputation for scroll tracking.
|
||||
* Returns null when the section is fully off-screen (freeze at last position).
|
||||
*/
|
||||
export function computeDualAnchor(
|
||||
section: AISection,
|
||||
): { x: number; y: number; width: number } | null {
|
||||
const el = section.ref.current;
|
||||
if (!el) return null;
|
||||
|
||||
// Skip scroll tracking for right-margin mode (stays at fixed clickY)
|
||||
if (section.anchorMode === 'right-margin') return null;
|
||||
|
||||
const rect = el.getBoundingClientRect();
|
||||
const w = getChatWidth();
|
||||
|
||||
// Fully off-screen — freeze
|
||||
if (rect.bottom < 0 || rect.top > window.innerHeight) return null;
|
||||
|
||||
// Primary anchor: top-right (when section top is visible)
|
||||
if (rect.top >= PADDING) {
|
||||
const { x, y } = clampPosition(
|
||||
rect.right - w - PADDING,
|
||||
rect.top + PADDING,
|
||||
);
|
||||
return { x, y, width: w };
|
||||
}
|
||||
|
||||
// Fallback anchor: bottom-right (when section top scrolled off)
|
||||
if (rect.bottom > CHAT_HEIGHT) {
|
||||
const { x, y } = clampPosition(
|
||||
rect.right - w - PADDING,
|
||||
rect.bottom - CHAT_HEIGHT - PADDING,
|
||||
);
|
||||
return { x, y, width: w };
|
||||
}
|
||||
|
||||
// Section visible but too small for fallback — clamp to top
|
||||
const { x, y } = clampPosition(
|
||||
rect.right - w - PADDING,
|
||||
PADDING,
|
||||
);
|
||||
return { x, y, width: w };
|
||||
}
|
||||
|
||||
// ---------- Context ----------
|
||||
|
||||
const FloatingChatCtx = createContext<FloatingChatContextValue | null>(null);
|
||||
|
||||
export function useFloatingChat(): FloatingChatContextValue {
|
||||
const ctx = useContext(FloatingChatCtx);
|
||||
if (!ctx)
|
||||
throw new Error('useFloatingChat must be used within FloatingChatProvider');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
// ---------- Provider ----------
|
||||
|
||||
export function FloatingChatProvider({ children }: { children: ReactNode }) {
|
||||
const sectionsRef = useRef<Map<string, AISection>>(new Map());
|
||||
const [sections, setSections] = useState<Map<string, AISection>>(new Map());
|
||||
const [state, setState] = useState<FloatingChatState>({
|
||||
isOpen: false,
|
||||
activeSectionId: null,
|
||||
position: { x: 0, y: 0, width: getChatWidth() },
|
||||
morphTargetId: null,
|
||||
});
|
||||
|
||||
const registerSection = useCallback((section: AISection) => {
|
||||
sectionsRef.current.set(section.id, section);
|
||||
setSections(new Map(sectionsRef.current));
|
||||
|
||||
// Check if there's a pending section to open after cross-page navigation
|
||||
setState((prev) => {
|
||||
if (prev.pendingSection && prev.pendingSection.sectionId === section.id) {
|
||||
const position = computeAnchorPosition(section, { clickY: prev.pendingSection.clickY });
|
||||
return {
|
||||
...prev,
|
||||
isOpen: true,
|
||||
activeSectionId: section.id,
|
||||
position,
|
||||
morphTargetId: null,
|
||||
projectId: section.projectId,
|
||||
pendingSection: undefined,
|
||||
};
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const unregisterSection = useCallback((id: string) => {
|
||||
sectionsRef.current.delete(id);
|
||||
setSections(new Map(sectionsRef.current));
|
||||
}, []);
|
||||
|
||||
const openAtSection = useCallback((sectionId: string, opts?: SectionOpenOpts) => {
|
||||
const section = sectionsRef.current.get(sectionId);
|
||||
if (!section) return;
|
||||
|
||||
const position = computeAnchorPosition(section, opts);
|
||||
|
||||
setState({
|
||||
isOpen: true,
|
||||
activeSectionId: sectionId,
|
||||
position,
|
||||
morphTargetId: null,
|
||||
projectId: section.projectId,
|
||||
});
|
||||
}, []);
|
||||
|
||||
const moveToSection = useCallback((sectionId: string, opts?: SectionOpenOpts) => {
|
||||
const section = sectionsRef.current.get(sectionId);
|
||||
if (!section) return;
|
||||
|
||||
const position = computeAnchorPosition(section, opts);
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
activeSectionId: sectionId,
|
||||
position,
|
||||
projectId: section.projectId,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const close = useCallback(() => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
isOpen: false,
|
||||
activeSectionId: null,
|
||||
morphTargetId: null,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setMorphTarget = useCallback((id: string | null) => {
|
||||
setState((prev) => ({ ...prev, morphTargetId: id }));
|
||||
}, []);
|
||||
|
||||
const updatePosition = useCallback((pos: { x: number; y: number; width: number }) => {
|
||||
setState((prev) => ({ ...prev, position: pos }));
|
||||
}, []);
|
||||
|
||||
const setPendingSection = useCallback((pending: { sectionId: string; clickY?: number } | undefined) => {
|
||||
setState((prev) => ({ ...prev, pendingSection: pending }));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<FloatingChatCtx.Provider
|
||||
value={{
|
||||
state,
|
||||
sections,
|
||||
registerSection,
|
||||
unregisterSection,
|
||||
openAtSection,
|
||||
moveToSection,
|
||||
close,
|
||||
setMorphTarget,
|
||||
updatePosition,
|
||||
setPendingSection,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</FloatingChatCtx.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
@import '@fontsource/geist/300.css';
|
||||
@import '@fontsource/geist/400.css';
|
||||
@import '@fontsource/geist/500.css';
|
||||
@import '@fontsource/geist/600.css';
|
||||
@import '@fontsource/geist/700.css';
|
||||
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
@plugin "@tailwindcss/typography";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@@ -49,73 +52,113 @@
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.141 0.005 285.823);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.141 0.005 285.823);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.141 0.005 285.823);
|
||||
--primary: oklch(0.21 0.006 285.885);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.967 0.001 286.375);
|
||||
--secondary-foreground: oklch(0.21 0.006 285.885);
|
||||
--muted: oklch(0.967 0.001 286.375);
|
||||
--muted-foreground: oklch(0.552 0.016 285.938);
|
||||
--accent: oklch(0.967 0.001 286.375);
|
||||
--accent-foreground: oklch(0.21 0.006 285.885);
|
||||
|
||||
/* #f4edf3 - Light Pinkish-White Canvas */
|
||||
--background: oklch(0.945 0.012 328.5);
|
||||
/* #040404 - Almost Black Text */
|
||||
--foreground: oklch(0.145 0 0);
|
||||
|
||||
--card: oklch(0.945 0.012 328.5);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(0.945 0.012 328.5);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
|
||||
/* #fbc881 - Golden Yellow Accent */
|
||||
--primary: oklch(0.838 0.117 76.8);
|
||||
--primary-foreground: oklch(0.145 0 0);
|
||||
|
||||
/* #8a8ea9 - Slate Blue/Gray */
|
||||
--secondary: oklch(0.627 0.041 274.5);
|
||||
--secondary-foreground: oklch(0.945 0.012 328.5);
|
||||
|
||||
/* #c8c3cd - Light Gray/Purple */
|
||||
--muted: oklch(0.811 0.014 300.2);
|
||||
--muted-foreground: oklch(0.627 0.041 274.5);
|
||||
|
||||
--accent: oklch(0.811 0.014 300.2);
|
||||
--accent-foreground: oklch(0.145 0 0);
|
||||
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--destructive-foreground: oklch(0.985 0 0);
|
||||
--border: oklch(0.92 0.004 286.32);
|
||||
--input: oklch(0.92 0.004 286.32);
|
||||
--ring: oklch(0.705 0.015 286.067);
|
||||
|
||||
--border: oklch(0.811 0.014 300.2);
|
||||
--input: oklch(0.811 0.014 300.2);
|
||||
--ring: oklch(0.838 0.117 76.8);
|
||||
|
||||
/* Kept your original chart colors */
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.141 0.005 285.823);
|
||||
--sidebar-primary: oklch(0.21 0.006 285.885);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.967 0.001 286.375);
|
||||
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
|
||||
--sidebar-border: oklch(0.92 0.004 286.32);
|
||||
--sidebar-ring: oklch(0.705 0.015 286.067);
|
||||
|
||||
/* Sidebar uses the custom palette */
|
||||
--sidebar: oklch(0.945 0.012 328.5);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.838 0.117 76.8);
|
||||
--sidebar-primary-foreground: oklch(0.145 0 0);
|
||||
--sidebar-accent: oklch(0.811 0.014 300.2);
|
||||
--sidebar-accent-foreground: oklch(0.145 0 0);
|
||||
--sidebar-border: oklch(0.811 0.014 300.2);
|
||||
--sidebar-ring: oklch(0.838 0.117 76.8);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.141 0.005 285.823);
|
||||
/* #0c0c0c - Deepest black for the main canvas */
|
||||
--background: oklch(0.15 0 0);
|
||||
/* #fbfbfb - Crisp white for primary text */
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.21 0.006 285.885);
|
||||
|
||||
/* Cards use the main background but are defined by borders */
|
||||
--card: oklch(0.15 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.21 0.006 285.885);
|
||||
--popover: oklch(0.15 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.92 0.004 286.32);
|
||||
--primary-foreground: oklch(0.21 0.006 285.885);
|
||||
--secondary: oklch(0.274 0.006 286.033);
|
||||
|
||||
/* #fbfbfb - Primary actions (like the active white circle menu item) */
|
||||
--primary: oklch(0.985 0 0);
|
||||
/* #0c0c0c - Dark text/icons inside primary buttons */
|
||||
--primary-foreground: oklch(0.15 0 0);
|
||||
|
||||
/* #323232 - Dark gray for secondary surfaces and button backgrounds */
|
||||
--secondary: oklch(0.335 0 0);
|
||||
/* #fbfbfb - White text on secondary surfaces */
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.274 0.006 286.033);
|
||||
--muted-foreground: oklch(0.705 0.015 286.067);
|
||||
--accent: oklch(0.274 0.006 286.033);
|
||||
|
||||
/* #323232 - Dark gray for muted backgrounds */
|
||||
--muted: oklch(0.335 0 0);
|
||||
/* #77797b - Mid gray for muted/secondary text (like "ELEVATE YOUR...") */
|
||||
--muted-foreground: oklch(0.555 0 0);
|
||||
|
||||
/* #323232 - Hover states */
|
||||
--accent: oklch(0.335 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
|
||||
--destructive: oklch(0.704 0.191 22.216); /* Kept original dark red */
|
||||
--destructive-foreground: oklch(0.985 0 0);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.552 0.016 285.938);
|
||||
|
||||
/* #323232 - Distinct dark gray borders for the cards/panels */
|
||||
--border: oklch(0.335 0 0);
|
||||
--input: oklch(0.335 0 0);
|
||||
/* #bab7ba - Lighter gray for focus rings to stand out against dark borders */
|
||||
--ring: oklch(0.765 0 0);
|
||||
|
||||
/* Kept your original chart colors */
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.21 0.006 285.885);
|
||||
|
||||
/* Sidebar mapped to the new sleek dark palette */
|
||||
--sidebar: oklch(0.15 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.274 0.006 286.033);
|
||||
--sidebar-primary: oklch(0.985 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.15 0 0);
|
||||
--sidebar-accent: oklch(0.335 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.552 0.016 285.938);
|
||||
--sidebar-border: oklch(0.335 0 0);
|
||||
--sidebar-ring: oklch(0.765 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
@@ -128,7 +171,7 @@
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Geist', 'Inter', system-ui, sans-serif;
|
||||
font-family: 'Geist', 'Inter', system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Noto Color Emoji';
|
||||
-webkit-font-smoothing: antialiased;
|
||||
margin: 0;
|
||||
overflow: hidden; /* Electron: no OS scrollbars */
|
||||
@@ -140,3 +183,120 @@ body {
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* ---- Glass Surface (ReactBits-style) ---- */
|
||||
/*
|
||||
* Gradient border via padding-box/border-box background split —
|
||||
* most reliable technique in Chromium/Electron; no pseudo-element mask needed.
|
||||
*/
|
||||
.glass-surface {
|
||||
border: 1px solid transparent;
|
||||
background:
|
||||
/* glass fill — clips to padding-box (inside the border) */
|
||||
rgba(255, 255, 255, 0.55) padding-box,
|
||||
/* gradient border — clips to border-box (the 1px border strip) */
|
||||
linear-gradient(
|
||||
145deg,
|
||||
rgba(255, 255, 255, 0.90) 0%,
|
||||
rgba(200, 195, 205, 0.40) 40%,
|
||||
rgba(200, 195, 205, 0.20) 100%
|
||||
) border-box;
|
||||
backdrop-filter: blur(24px) saturate(180%);
|
||||
-webkit-backdrop-filter: blur(24px) saturate(180%);
|
||||
box-shadow:
|
||||
0 4px 48px rgba(0, 0, 0, 0.10),
|
||||
0 1px 2px rgba(0, 0, 0, 0.06),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.80);
|
||||
}
|
||||
|
||||
.dark .glass-surface {
|
||||
background:
|
||||
rgba(255, 255, 255, 0.05) padding-box,
|
||||
linear-gradient(
|
||||
145deg,
|
||||
rgba(255, 255, 255, 0.18) 0%,
|
||||
rgba(255, 255, 255, 0.04) 40%,
|
||||
rgba(255, 255, 255, 0.08) 100%
|
||||
) border-box;
|
||||
box-shadow:
|
||||
0 4px 48px rgba(0, 0, 0, 0.50),
|
||||
0 1px 2px rgba(0, 0, 0, 0.20),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.10);
|
||||
}
|
||||
|
||||
/* Subtle variant — same gradient border, much more transparent fill */
|
||||
.glass-surface-subtle {
|
||||
border: 1px solid transparent;
|
||||
background:
|
||||
rgba(255, 255, 255, 0.20) padding-box,
|
||||
linear-gradient(
|
||||
145deg,
|
||||
rgba(255, 255, 255, 0.70) 0%,
|
||||
rgba(200, 195, 205, 0.25) 40%,
|
||||
rgba(200, 195, 205, 0.10) 100%
|
||||
) border-box;
|
||||
backdrop-filter: blur(16px) saturate(160%);
|
||||
-webkit-backdrop-filter: blur(16px) saturate(160%);
|
||||
box-shadow:
|
||||
0 2px 12px rgba(0, 0, 0, 0.06),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.60);
|
||||
}
|
||||
|
||||
.dark .glass-surface-subtle {
|
||||
background:
|
||||
rgba(255, 255, 255, 0.03) padding-box,
|
||||
linear-gradient(
|
||||
145deg,
|
||||
rgba(255, 255, 255, 0.12) 0%,
|
||||
rgba(255, 255, 255, 0.02) 40%,
|
||||
rgba(255, 255, 255, 0.05) 100%
|
||||
) border-box;
|
||||
box-shadow:
|
||||
0 2px 12px rgba(0, 0, 0, 0.30),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.07);
|
||||
}
|
||||
|
||||
/* Crepe editor layout */
|
||||
.milkdown-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.milkdown-container .milkdown {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
--crepe-color-background: var(--background);
|
||||
--crepe-font-default: 'Geist', 'Inter', system-ui, sans-serif;
|
||||
--crepe-font-title: 'Geist', 'Inter', system-ui, sans-serif;
|
||||
}
|
||||
|
||||
/* Override Crepe's default 60px 120px padding for panel use.
|
||||
Left padding >=72px to leave room for the block handle (plus + drag buttons). */
|
||||
.milkdown-container .milkdown .ProseMirror {
|
||||
@apply pr-6 pl-18 py-0;
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* Dark theme: scope nord-dark variables under .dark class */
|
||||
.dark .milkdown {
|
||||
--crepe-color-on-background: #f8f9ff;
|
||||
--crepe-color-surface: #111418;
|
||||
--crepe-color-surface-low: #191c20;
|
||||
--crepe-color-on-surface: #e1e2e8;
|
||||
--crepe-color-on-surface-variant: #c3c6cf;
|
||||
--crepe-color-outline: #8d9199;
|
||||
--crepe-color-primary: #a1c9fd;
|
||||
--crepe-color-secondary: #3c4858;
|
||||
--crepe-color-on-secondary: #d7e3f8;
|
||||
--crepe-color-inverse: #e1e2e8;
|
||||
--crepe-color-on-inverse: #2e3135;
|
||||
--crepe-color-inline-code: #ffb4ab;
|
||||
--crepe-color-error: #ffb4ab;
|
||||
--crepe-color-hover: #1d2024;
|
||||
--crepe-color-selected: #32353a;
|
||||
--crepe-color-inline-area: #111418;
|
||||
--crepe-shadow-1: 0px 1px 2px 0px rgba(255, 255, 255, 0.3), 0px 1px 3px 1px rgba(255, 255, 255, 0.15);
|
||||
--crepe-shadow-2: 0px 1px 2px 0px rgba(255, 255, 255, 0.3), 0px 2px 6px 2px rgba(255, 255, 255, 0.15);
|
||||
}
|
||||
|
||||
142
src/renderer/hooks/useAIChat.ts
Normal file
142
src/renderer/hooks/useAIChat.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { useState, useCallback, useRef } from 'react';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
|
||||
interface ChatMessage {
|
||||
id: string;
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
error?: boolean;
|
||||
}
|
||||
|
||||
export interface ChatContext {
|
||||
type: 'global' | 'project';
|
||||
projectId?: string;
|
||||
uiContext?: string;
|
||||
}
|
||||
|
||||
interface UseAIChatReturn {
|
||||
messages: ChatMessage[];
|
||||
input: string;
|
||||
setInput: (v: string) => void;
|
||||
isStreaming: boolean;
|
||||
streamingContent: string;
|
||||
handleSend: (overrideMessage?: string, overrideContext?: ChatContext) => void;
|
||||
clearMessages: () => void;
|
||||
}
|
||||
|
||||
interface UseAIChatOptions {
|
||||
onSectionTag?: (sectionId: string) => void;
|
||||
}
|
||||
|
||||
export function useAIChat(defaultContext: ChatContext, options?: UseAIChatOptions): UseAIChatReturn {
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [isStreaming, setIsStreaming] = useState(false);
|
||||
const [streamingContent, setStreamingContent] = useState('');
|
||||
|
||||
const streamingContentRef = useRef('');
|
||||
const chatMutation = trpc.ai.chat.useMutation();
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
setStreamingContent('');
|
||||
streamingContentRef.current = '';
|
||||
}, []);
|
||||
|
||||
const handleSend = useCallback(
|
||||
(overrideMessage?: string, overrideContext?: ChatContext) => {
|
||||
const trimmed = (overrideMessage ?? input).trim();
|
||||
if (!trimmed || isStreaming) return;
|
||||
|
||||
const userMsg: ChatMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
role: 'user',
|
||||
content: trimmed,
|
||||
};
|
||||
|
||||
setMessages((prev) => [...prev, userMsg]);
|
||||
if (!overrideMessage) setInput('');
|
||||
setIsStreaming(true);
|
||||
setStreamingContent('');
|
||||
streamingContentRef.current = '';
|
||||
|
||||
const unsubscribe = window.electronAI.onStreamChunk(({ token, done }) => {
|
||||
if (done) {
|
||||
let finalContent = streamingContentRef.current;
|
||||
|
||||
// Parse and strip [SECTION:xxx] tag from AI response
|
||||
const sectionMatch = finalContent.match(/^\[SECTION:([\w-]+)\]\s*/);
|
||||
if (sectionMatch) {
|
||||
finalContent = finalContent.slice(sectionMatch[0].length);
|
||||
options?.onSectionTag?.(sectionMatch[1]!);
|
||||
}
|
||||
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ id: crypto.randomUUID(), role: 'assistant', content: finalContent },
|
||||
]);
|
||||
setStreamingContent('');
|
||||
streamingContentRef.current = '';
|
||||
setIsStreaming(false);
|
||||
unsubscribe();
|
||||
return;
|
||||
}
|
||||
streamingContentRef.current += token;
|
||||
setStreamingContent(streamingContentRef.current);
|
||||
});
|
||||
|
||||
const ctx = overrideContext ?? defaultContext;
|
||||
|
||||
chatMutation.mutate(
|
||||
{
|
||||
message: trimmed,
|
||||
context: {
|
||||
type: ctx.type,
|
||||
...(ctx.type === 'project' && ctx.projectId ? { projectId: ctx.projectId } : {}),
|
||||
...(ctx.uiContext ? { uiContext: ctx.uiContext } : {}),
|
||||
},
|
||||
},
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
if (data.error) {
|
||||
unsubscribe();
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ id: crypto.randomUUID(), role: 'assistant', content: data.error!, error: true },
|
||||
]);
|
||||
setStreamingContent('');
|
||||
streamingContentRef.current = '';
|
||||
setIsStreaming(false);
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
unsubscribe();
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
role: 'assistant',
|
||||
content: err.message || 'An unexpected error occurred.',
|
||||
error: true,
|
||||
},
|
||||
]);
|
||||
setStreamingContent('');
|
||||
streamingContentRef.current = '';
|
||||
setIsStreaming(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
},
|
||||
[input, isStreaming, defaultContext, chatMutation],
|
||||
);
|
||||
|
||||
return {
|
||||
messages,
|
||||
input,
|
||||
setInput,
|
||||
isStreaming,
|
||||
streamingContent,
|
||||
handleSend,
|
||||
clearMessages,
|
||||
};
|
||||
}
|
||||
54
src/renderer/hooks/useDoubleClickAI.ts
Normal file
54
src/renderer/hooks/useDoubleClickAI.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useFloatingChat } from '@/context/FloatingChatContext';
|
||||
|
||||
// Elements where double-click should NOT trigger the AI popup
|
||||
const INTERACTIVE_TAGS = new Set(['INPUT', 'TEXTAREA', 'SELECT']);
|
||||
|
||||
export function useDoubleClickAI(): void {
|
||||
const { openAtSection, moveToSection, sections, state } = useFloatingChat();
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: MouseEvent) => {
|
||||
const target = e.target as HTMLElement;
|
||||
|
||||
// Skip interactive elements (preserve text selection behavior)
|
||||
if (INTERACTIVE_TAGS.has(target.tagName)) return;
|
||||
|
||||
// Skip contenteditable elements UNLESS they're inside Milkdown
|
||||
if (target.isContentEditable) {
|
||||
const inMilkdown =
|
||||
target.closest('.milkdown-container') ||
|
||||
target.closest('.crepe-editor');
|
||||
if (!inMilkdown) return;
|
||||
// For Milkdown: only trigger if no text was selected by the double-click
|
||||
const selection = window.getSelection();
|
||||
if (selection && selection.toString().trim().length > 0) return;
|
||||
}
|
||||
|
||||
// Walk up DOM to find nearest [data-ai-section]
|
||||
const sectionEl = (target as Element).closest('[data-ai-section]');
|
||||
if (!sectionEl) return;
|
||||
|
||||
const sectionId = sectionEl.getAttribute('data-ai-section');
|
||||
if (!sectionId) return;
|
||||
|
||||
// If popup is already open at THIS section, do nothing
|
||||
if (state.isOpen && state.activeSectionId === sectionId) return;
|
||||
|
||||
// Build opts for right-margin sections
|
||||
const section = sections.get(sectionId);
|
||||
const opts = section?.anchorMode === 'right-margin' ? { clickY: e.clientY } : undefined;
|
||||
|
||||
// If chat is already open at a different section, move (keep conversation)
|
||||
if (state.isOpen) {
|
||||
moveToSection(sectionId, opts);
|
||||
return;
|
||||
}
|
||||
|
||||
openAtSection(sectionId, opts);
|
||||
};
|
||||
|
||||
document.addEventListener('dblclick', handler);
|
||||
return () => document.removeEventListener('dblclick', handler);
|
||||
}, [openAtSection, moveToSection, sections, state.isOpen, state.activeSectionId]);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { ipcLink } from './lib/ipcLink';
|
||||
import { router } from './router';
|
||||
import { trpc } from './lib/trpc';
|
||||
import { ThemeProvider } from './components/theme-provider';
|
||||
import './globals.css';
|
||||
|
||||
function App() {
|
||||
@@ -16,11 +17,13 @@ function App() {
|
||||
);
|
||||
|
||||
return (
|
||||
<ThemeProvider defaultTheme="system" storageKey="adiuva-theme">
|
||||
<trpc.Provider client={trpcClient} queryClient={queryClient}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>
|
||||
</trpc.Provider>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,9 +13,15 @@ interface ElectronTRPC {
|
||||
onMessage: (cb: (data: unknown) => void) => (() => void) | void;
|
||||
}
|
||||
|
||||
interface ElectronAI {
|
||||
onStreamChunk: (cb: (data: { token: string; done: boolean }) => void) => () => void;
|
||||
onAction: (cb: (data: { type: string; taskId?: string; count?: number }) => void) => () => void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
electronTRPC: ElectronTRPC;
|
||||
electronAI: ElectronAI;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Route as TimelineRouteImport } from './routes/timeline'
|
||||
import { Route as TasksRouteImport } from './routes/tasks'
|
||||
import { Route as ProjectsRouteImport } from './routes/projects'
|
||||
import { Route as IndexRouteImport } from './routes/index'
|
||||
import { Route as NotesNoteIdRouteImport } from './routes/notes.$noteId'
|
||||
|
||||
const TimelineRoute = TimelineRouteImport.update({
|
||||
id: '/timeline',
|
||||
@@ -34,18 +35,25 @@ const IndexRoute = IndexRouteImport.update({
|
||||
path: '/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const NotesNoteIdRoute = NotesNoteIdRouteImport.update({
|
||||
id: '/notes/$noteId',
|
||||
path: '/notes/$noteId',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
'/projects': typeof ProjectsRoute
|
||||
'/tasks': typeof TasksRoute
|
||||
'/timeline': typeof TimelineRoute
|
||||
'/notes/$noteId': typeof NotesNoteIdRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
'/projects': typeof ProjectsRoute
|
||||
'/tasks': typeof TasksRoute
|
||||
'/timeline': typeof TimelineRoute
|
||||
'/notes/$noteId': typeof NotesNoteIdRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
@@ -53,13 +61,14 @@ export interface FileRoutesById {
|
||||
'/projects': typeof ProjectsRoute
|
||||
'/tasks': typeof TasksRoute
|
||||
'/timeline': typeof TimelineRoute
|
||||
'/notes/$noteId': typeof NotesNoteIdRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths: '/' | '/projects' | '/tasks' | '/timeline'
|
||||
fullPaths: '/' | '/projects' | '/tasks' | '/timeline' | '/notes/$noteId'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/' | '/projects' | '/tasks' | '/timeline'
|
||||
id: '__root__' | '/' | '/projects' | '/tasks' | '/timeline'
|
||||
to: '/' | '/projects' | '/tasks' | '/timeline' | '/notes/$noteId'
|
||||
id: '__root__' | '/' | '/projects' | '/tasks' | '/timeline' | '/notes/$noteId'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
@@ -67,6 +76,7 @@ export interface RootRouteChildren {
|
||||
ProjectsRoute: typeof ProjectsRoute
|
||||
TasksRoute: typeof TasksRoute
|
||||
TimelineRoute: typeof TimelineRoute
|
||||
NotesNoteIdRoute: typeof NotesNoteIdRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
@@ -99,6 +109,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof IndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/notes/$noteId': {
|
||||
id: '/notes/$noteId'
|
||||
path: '/notes/$noteId'
|
||||
fullPath: '/notes/$noteId'
|
||||
preLoaderRoute: typeof NotesNoteIdRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,6 +124,7 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
ProjectsRoute: ProjectsRoute,
|
||||
TasksRoute: TasksRoute,
|
||||
TimelineRoute: TimelineRoute,
|
||||
NotesNoteIdRoute: NotesNoteIdRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
|
||||
@@ -1,40 +1,5 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
|
||||
export const Route = createFileRoute('/')({
|
||||
component: HomePage,
|
||||
component: () => null,
|
||||
});
|
||||
|
||||
function HomePage() {
|
||||
const pingQuery = trpc.health.ping.useQuery();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
className="text-foreground"
|
||||
>
|
||||
<path
|
||||
d="M12 2L13.5 8.5L20 10L13.5 11.5L12 18L10.5 11.5L4 10L10.5 8.5L12 2Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
<h1 className="text-3xl font-semibold tracking-tight">
|
||||
Hello, Roberto
|
||||
</h1>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Adiuva is ready. Start building.
|
||||
</p>
|
||||
{pingQuery.data && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
tRPC IPC bridge: {pingQuery.data}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
218
src/renderer/routes/notes.$noteId.tsx
Normal file
218
src/renderer/routes/notes.$noteId.tsx
Normal file
@@ -0,0 +1,218 @@
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { ArrowLeft, Trash2 } from 'lucide-react';
|
||||
import { format } from 'date-fns';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { MilkdownEditor } from '@/components/notes/MilkdownEditor';
|
||||
import { useFloatingChat } from '@/context/FloatingChatContext';
|
||||
|
||||
export const Route = createFileRoute('/notes/$noteId')({
|
||||
component: NoteDetailPage,
|
||||
});
|
||||
|
||||
function NoteDetailPage() {
|
||||
const { noteId } = Route.useParams();
|
||||
const utils = trpc.useUtils();
|
||||
const { data: note, isLoading } = trpc.notes.get.useQuery({ id: noteId });
|
||||
|
||||
// AI section — register with right-margin anchor mode
|
||||
const editorRef = useRef<HTMLDivElement>(null);
|
||||
const { registerSection, unregisterSection } = useFloatingChat();
|
||||
const noteProjectId = note?.projectId ?? undefined;
|
||||
useEffect(() => {
|
||||
registerSection({
|
||||
id: 'note-editor',
|
||||
label: 'Note Editor',
|
||||
ref: editorRef,
|
||||
projectId: noteProjectId,
|
||||
anchorMode: 'right-margin',
|
||||
});
|
||||
return () => unregisterSection('note-editor');
|
||||
}, [noteId, noteProjectId, registerSection, unregisterSection]);
|
||||
|
||||
const [title, setTitle] = useState('');
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// Store the latest markdown so we can flush it on back navigation
|
||||
const pendingContentRef = useRef<string | null>(null);
|
||||
|
||||
const updateNote = trpc.notes.update.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.notes.get.invalidate({ id: noteId });
|
||||
void utils.notes.list.invalidate();
|
||||
},
|
||||
onSettled: () => {
|
||||
setIsSaving(false);
|
||||
},
|
||||
});
|
||||
|
||||
const deleteNote = trpc.notes.delete.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.notes.list.invalidate();
|
||||
window.history.back();
|
||||
},
|
||||
});
|
||||
|
||||
// Sync title from server data on initial load
|
||||
useEffect(() => {
|
||||
if (note) {
|
||||
setTitle(note.title);
|
||||
}
|
||||
}, [note]);
|
||||
|
||||
// Cleanup debounce timer on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleContentChange = useCallback(
|
||||
(markdown: string) => {
|
||||
setIsSaving(true);
|
||||
pendingContentRef.current = markdown;
|
||||
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
}
|
||||
|
||||
debounceTimerRef.current = setTimeout(() => {
|
||||
pendingContentRef.current = null;
|
||||
updateNote.mutate({ id: noteId, content: markdown });
|
||||
}, 2000);
|
||||
},
|
||||
[noteId, updateNote]
|
||||
);
|
||||
|
||||
const handleTitleBlur = () => {
|
||||
const trimmed = title.trim();
|
||||
if (trimmed && note && trimmed !== note.title) {
|
||||
setIsSaving(true);
|
||||
updateNote.mutate({ id: noteId, title: trimmed });
|
||||
}
|
||||
};
|
||||
|
||||
const handleTitleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.currentTarget.blur();
|
||||
}
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
// Flush any pending debounced save immediately before navigating
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
debounceTimerRef.current = null;
|
||||
}
|
||||
if (pendingContentRef.current !== null) {
|
||||
updateNote.mutate({ id: noteId, content: pendingContentRef.current });
|
||||
pendingContentRef.current = null;
|
||||
}
|
||||
window.history.back();
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
// Cancel any pending save before deleting
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
debounceTimerRef.current = null;
|
||||
}
|
||||
pendingContentRef.current = null;
|
||||
deleteNote.mutate({ id: noteId });
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-muted-foreground text-sm">Loading note...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!note) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-muted-foreground text-sm">Note not found.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-2 border-b border-border px-4 py-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleBack}
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<Input
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
onBlur={handleTitleBlur}
|
||||
onKeyDown={handleTitleKeyDown}
|
||||
className="border-0 shadow-none text-2xl font-semibold focus-visible:ring-0 px-0 h-auto"
|
||||
placeholder="Untitled Note"
|
||||
/>
|
||||
{isSaving && <Badge variant="secondary">Saving...</Badge>}
|
||||
<span className="text-muted-foreground text-xs whitespace-nowrap">
|
||||
Last edited {format(new Date(note.updatedAt), 'MMM d, yyyy · h:mm a')}
|
||||
</span>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={deleteNote.isPending}
|
||||
>
|
||||
<Trash2 /> Delete
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete note</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete "{title || 'Untitled Note'}"? This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={handleDelete}>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
|
||||
{/* Editor */}
|
||||
<ScrollArea ref={editorRef} data-ai-section="note-editor" className="flex-1 min-h-0">
|
||||
<div className="px-4 py-4">
|
||||
<MilkdownEditor
|
||||
key={noteId}
|
||||
initialContent={note.content}
|
||||
onChange={handleContentChange}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { z } from 'zod';
|
||||
import { FolderKanban } from 'lucide-react';
|
||||
import { ProjectSidebar } from '@/components/projects/ProjectSidebar';
|
||||
import { ProjectDetail } from '@/components/projects/ProjectDetail';
|
||||
import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription } from '@/components/ui/empty';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
|
||||
const searchSchema = z.object({
|
||||
projectId: z.string().optional(),
|
||||
@@ -26,15 +29,23 @@ function ProjectsPage() {
|
||||
selectedProjectId={projectId}
|
||||
onSelectProject={handleSelectProject}
|
||||
/>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<ScrollArea className="flex-1">
|
||||
{projectId ? (
|
||||
<ProjectDetail projectId={projectId} />
|
||||
) : (
|
||||
<div className="flex-1 flex items-center justify-center h-full text-sm text-muted-foreground">
|
||||
Select a project to view details
|
||||
</div>
|
||||
<Empty className="h-full">
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant="icon">
|
||||
<FolderKanban />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>No project selected</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
Select a project from the sidebar to view its details.
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { useState, useCallback, useMemo } from 'react';
|
||||
import { useState, useCallback, useMemo, useRef, useEffect } from 'react';
|
||||
import { useFloatingChat } from '@/context/FloatingChatContext';
|
||||
import {
|
||||
ClipboardCheck,
|
||||
ListTodo,
|
||||
Loader2,
|
||||
Clock,
|
||||
CheckCircle2,
|
||||
Plus,
|
||||
Search,
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription } from '@/components/ui/empty';
|
||||
import { NewTaskDialog } from '@/components/tasks/NewTaskDialog';
|
||||
import { EditTaskDialog } from '@/components/tasks/EditTaskDialog';
|
||||
import { TaskDetailDialog } from '@/components/tasks/TaskDetailDialog';
|
||||
import { TaskRow, type TaskItem } from '@/components/tasks/TaskRow';
|
||||
|
||||
export const Route = createFileRoute('/tasks')({
|
||||
@@ -39,12 +41,26 @@ const ORDER_LABELS: Record<OrderBy, string> = {
|
||||
};
|
||||
|
||||
function TasksPage() {
|
||||
// AI section refs
|
||||
const overviewRef = useRef<HTMLDivElement>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const { state: floatingState, registerSection, unregisterSection } = useFloatingChat();
|
||||
useEffect(() => {
|
||||
registerSection({ id: 'tasks-overview', label: 'Tasks Overview', ref: overviewRef });
|
||||
registerSection({ id: 'tasks-list', label: 'Task List', ref: listRef });
|
||||
return () => {
|
||||
unregisterSection('tasks-overview');
|
||||
unregisterSection('tasks-list');
|
||||
};
|
||||
}, [registerSection, unregisterSection]);
|
||||
|
||||
const [search, setSearch] = useState('');
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
|
||||
const [orderBy, setOrderBy] = useState<OrderBy>('createdAt');
|
||||
const [orderBy, setOrderBy] = useState<OrderBy>('dueDate');
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editTask, setEditTask] = useState<TaskItem | null>(null);
|
||||
const [viewTask, setViewTask] = useState<TaskItem | null>(null);
|
||||
|
||||
const debounceTimer = useMemo(() => ({ id: null as ReturnType<typeof setTimeout> | null }), []);
|
||||
|
||||
@@ -82,7 +98,9 @@ function TasksPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const tasksList = filteredTasks ?? [];
|
||||
const tasksList = (filteredTasks ?? []).filter(
|
||||
(t) => !(t.isAiSuggested === 1 && t.isApproved === 0),
|
||||
);
|
||||
|
||||
// Compute stats from all tasks (unfiltered)
|
||||
const stats = useMemo(() => {
|
||||
@@ -106,9 +124,9 @@ function TasksPage() {
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 p-6 max-w-[1200px] mx-auto w-full">
|
||||
<div className="flex flex-col gap-6 p-6 w-full">
|
||||
{/* Stat Cards */}
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
<div ref={overviewRef} data-ai-section="tasks-overview" className="grid grid-cols-4 gap-4">
|
||||
<Item variant="muted">
|
||||
<ItemMedia variant="icon">
|
||||
<ClipboardCheck />
|
||||
@@ -127,16 +145,16 @@ function TasksPage() {
|
||||
<ItemDescription>To Do</ItemDescription>
|
||||
</ItemContent>
|
||||
</Item>
|
||||
<Item variant="muted" className="bg-sky-50">
|
||||
<Item variant="muted" className="bg-sky-50 dark:bg-sky-950/30">
|
||||
<ItemMedia variant="icon">
|
||||
<Loader2 />
|
||||
<Clock />
|
||||
</ItemMedia>
|
||||
<ItemContent>
|
||||
<ItemTitle>{stats.inProgress}</ItemTitle>
|
||||
<ItemDescription>In Progress</ItemDescription>
|
||||
</ItemContent>
|
||||
</Item>
|
||||
<Item variant="muted" className="bg-green-50">
|
||||
<Item variant="muted" className="bg-green-50 dark:bg-green-950/30">
|
||||
<ItemMedia variant="icon">
|
||||
<CheckCircle2 />
|
||||
</ItemMedia>
|
||||
@@ -147,6 +165,8 @@ function TasksPage() {
|
||||
</Item>
|
||||
</div>
|
||||
|
||||
{/* Task List Section */}
|
||||
<div ref={listRef} data-ai-section="tasks-list" className="flex flex-col gap-6">
|
||||
{/* Search + Order By */}
|
||||
<div className="flex items-center gap-3">
|
||||
<InputGroup className="flex-1">
|
||||
@@ -211,10 +231,17 @@ function TasksPage() {
|
||||
onToggle={handleCheckboxToggle}
|
||||
onEdit={setEditTask}
|
||||
onDelete={(id) => deleteTask.mutate({ id })}
|
||||
onClick={setViewTask}
|
||||
layoutId={
|
||||
floatingState.morphTargetId === `task-morph-${task.id}`
|
||||
? floatingState.morphTargetId
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<NewTaskDialog open={dialogOpen} onOpenChange={setDialogOpen} />
|
||||
<EditTaskDialog
|
||||
@@ -222,6 +249,13 @@ function TasksPage() {
|
||||
open={!!editTask}
|
||||
onOpenChange={(open: boolean) => { if (!open) setEditTask(null); }}
|
||||
/>
|
||||
<TaskDetailDialog
|
||||
task={viewTask}
|
||||
open={!!viewTask}
|
||||
onOpenChange={(open) => { if (!open) setViewTask(null); }}
|
||||
onEdit={(task) => { setViewTask(null); setEditTask(task); }}
|
||||
onDelete={(id) => { deleteTask.mutate({ id }); setViewTask(null); }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
import { useState, useMemo } from 'react';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { useEffect, useRef, useState, useMemo } from 'react';
|
||||
import { Plus, ChartGantt } from 'lucide-react';
|
||||
import { useFloatingChat } from '@/context/FloatingChatContext';
|
||||
import { trpc } from '@/lib/trpc';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { GanttChart, type GanttCheckpoint } from '@/components/timeline/GanttChart';
|
||||
import { AddCheckpointDialog } from '@/components/timeline/AddCheckpointDialog';
|
||||
import { EditCheckpointDialog } from '@/components/timeline/EditCheckpointDialog';
|
||||
import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription } from '@/components/ui/empty';
|
||||
|
||||
export const Route = createFileRoute('/timeline')({
|
||||
component: TimelinePage,
|
||||
@@ -12,6 +15,15 @@ export const Route = createFileRoute('/timeline')({
|
||||
|
||||
function TimelinePage() {
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editingCheckpoint, setEditingCheckpoint] = useState<GanttCheckpoint | null>(null);
|
||||
|
||||
// AI section
|
||||
const timelineRef = useRef<HTMLDivElement>(null);
|
||||
const { registerSection, unregisterSection } = useFloatingChat();
|
||||
useEffect(() => {
|
||||
registerSection({ id: 'timeline-chart', label: 'Timeline', ref: timelineRef });
|
||||
return () => unregisterSection('timeline-chart');
|
||||
}, [registerSection, unregisterSection]);
|
||||
|
||||
const { data: checkpoints } = trpc.checkpoints.list.useQuery({});
|
||||
const { data: projectsList } = trpc.projects.listAll.useQuery();
|
||||
@@ -23,6 +35,12 @@ function TimelinePage() {
|
||||
},
|
||||
});
|
||||
|
||||
const updateCheckpoint = trpc.checkpoints.update.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.checkpoints.list.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
// Build project name lookup
|
||||
const projectMap = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
@@ -62,7 +80,7 @@ function TimelinePage() {
|
||||
}, [ganttCheckpoints]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 p-6 max-w-[1200px] mx-auto w-full">
|
||||
<div ref={timelineRef} data-ai-section="timeline-chart" className="flex flex-col gap-6 p-6 w-full">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold">Timeline</h1>
|
||||
@@ -75,36 +93,52 @@ function TimelinePage() {
|
||||
{/* Legend */}
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<svg width={14} height={14}><circle cx={7} cy={7} r={5} fill="#171717" /></svg>
|
||||
<svg width={14} height={14}><circle cx={7} cy={7} r={5} fill="var(--primary)" /></svg>
|
||||
To Do
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<svg width={14} height={14}><circle cx={7} cy={7} r={5} fill="#16a34a" /></svg>
|
||||
<svg width={14} height={14}><circle cx={7} cy={7} r={5} fill="var(--chart-2)" /></svg>
|
||||
Completed
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<svg width={14} height={14}><circle cx={7} cy={7} r={5} fill="none" stroke="#737373" strokeWidth={1.5} strokeDasharray="3 2" /></svg>
|
||||
<svg width={14} height={14}><circle cx={7} cy={7} r={5} fill="none" stroke="var(--muted-foreground)" strokeWidth={1.5} strokeDasharray="3 2" /></svg>
|
||||
AI Suggestion (Pending)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Gantt Chart */}
|
||||
{ganttCheckpoints.length === 0 ? (
|
||||
<div className="text-center text-muted-foreground text-sm py-12 border rounded-md bg-muted/30">
|
||||
No checkpoints yet. Click "+ Add" to create your first milestone.
|
||||
</div>
|
||||
<Empty>
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant="icon">
|
||||
<ChartGantt />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>No milestones yet</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
Click "+ Add" to create your first project checkpoint.
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
) : (
|
||||
<div className="border rounded-md p-4 bg-white">
|
||||
<div className="border rounded-md p-4 bg-card">
|
||||
<GanttChart
|
||||
checkpoints={ganttCheckpoints}
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
onDelete={(id) => deleteCheckpoint.mutate({ id })}
|
||||
onEdit={(cp) => setEditingCheckpoint(cp)}
|
||||
onToggleApproval={(id, current) =>
|
||||
updateCheckpoint.mutate({ id, isApproved: current === 1 ? 0 : 1 })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<AddCheckpointDialog open={dialogOpen} onOpenChange={setDialogOpen} />
|
||||
<EditCheckpointDialog
|
||||
checkpoint={editingCheckpoint}
|
||||
onOpenChange={(open) => { if (!open) setEditingCheckpoint(null); }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,19 @@ export default defineConfig({
|
||||
build: {
|
||||
rollupOptions: {
|
||||
// Externalize native Node modules — they're rebuilt by electron-forge
|
||||
external: ['better-sqlite3'],
|
||||
external: [
|
||||
'better-sqlite3',
|
||||
'@github/copilot-sdk',
|
||||
'@github/copilot',
|
||||
// LangChain — externalize to avoid bundling Node.js-specific code
|
||||
'@langchain/core',
|
||||
'@langchain/langgraph',
|
||||
'@langchain/openai',
|
||||
'@langchain/anthropic',
|
||||
'@langchain/langgraph-checkpoint',
|
||||
'@langchain/langgraph-sdk',
|
||||
'vectordb',
|
||||
],
|
||||
output: {
|
||||
entryFileNames: 'main.js',
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user