Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 154 additions & 0 deletions .kilocode/rules/overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# Wave Terminal - High Level Architecture Overview

## Project Description

Wave Terminal is an open-source AI-native terminal built for seamless workflows. It's an Electron application that serves as a command line terminal host (it hosts CLI applications rather than running inside a CLI). The application combines a React frontend with a Go backend server to provide a modern terminal experience with advanced features.

## Top-Level Directory Structure

```
waveterm/
├── emain/ # Electron main process code
├── frontend/ # React application (renderer process)
├── cmd/ # Go command-line applications
├── pkg/ # Go packages/modules
├── db/ # Database migrations
├── docs/ # Documentation (Docusaurus)
├── build/ # Build configuration and assets
├── assets/ # Application assets (icons, images)
├── public/ # Static public assets
├── tests/ # Test files
├── .github/ # GitHub workflows and configuration
└── Configuration files (package.json, tsconfig.json, etc.)
```
Comment on lines +9 to +23
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Add language identifiers to fenced code blocks.

Line 9 and Line 50 use unlabeled triple-backtick fences, which will keep triggering MD040 in markdownlint. Please label them (for example, text).

Suggested fix
-```
+```text
 waveterm/
 ├── emain/              # Electron main process code
 ...
 └── Configuration files (package.json, tsconfig.json, etc.)

- +text
frontend/
├── app/ # Main application code
...
└── util/ # Utility functions

</details>


Also applies to: 50-77

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.21.0)</summary>

[warning] 9-9: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

</details>

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @.kilocode/rules/overview.md around lines 9 - 23, The unlabeled fenced code
blocks containing the repository trees (the block starting with "waveterm/" and
the block starting with "frontend/") need language identifiers to satisfy
markdownlint MD040; edit the opening triple-backtick for those blocks (and any
similar block in the 50-77 range) to include a language tag such as text (e.g.,
change totext) so the examples are properly labeled; locate the blocks
by the unique lines "waveterm/" and "frontend/" to update their opening fences
accordingly.


</details>

<!-- fingerprinting:phantom:triton:hawk -->

<!-- This is an auto-generated comment by CodeRabbit -->


## Architecture Components

### 1. Electron Main Process (`emain/`)

The Electron main process handles the native desktop application layer:

**Key Files:**

- [`emain.ts`](emain/emain.ts) - Main entry point, application lifecycle management
- [`emain-window.ts`](emain/emain-window.ts) - Window management (`WaveBrowserWindow` class)
- [`emain-tabview.ts`](emain/emain-tabview.ts) - Tab view management (`WaveTabView` class)
- [`emain-wavesrv.ts`](emain/emain-wavesrv.ts) - Go backend server integration
- [`emain-wsh.ts`](emain/emain-wsh.ts) - WSH (Wave Shell) client integration
- [`emain-ipc.ts`](emain/emain-ipc.ts) - IPC handlers for frontend ↔ main process communication
- [`emain-menu.ts`](emain/emain-menu.ts) - Application menu system
- [`updater.ts`](emain/updater.ts) - Auto-update functionality
- [`preload.ts`](emain/preload.ts) - Preload script for renderer security
- [`preload-webview.ts`](emain/preload-webview.ts) - Webview preload script

Comment on lines +33 to +43
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix likely broken relative links in the architecture doc.

The links on Line 33–Line 43, Line 95, and Line 140–Line 145 appear to be relative to .kilocode/rules/, so they likely won’t resolve to repo files. Please update to correct relative paths (or stable absolute repo links) so navigation works from this file.

Also applies to: 95-95, 140-145

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.kilocode/rules/overview.md around lines 33 - 43, The listed markdown links
in .kilocode/rules/overview.md for files like emain.ts, emain-window.ts,
emain-tabview.ts, emain-wavesrv.ts, emain-wsh.ts, emain-ipc.ts, emain-menu.ts,
updater.ts, preload.ts, and preload-webview.ts are using paths relative to
.kilocode/rules/ and will not resolve; update those link targets to correct
repo-relative paths (e.g., ../../emain/emain.ts or the canonical repository
URLs) so they point to the actual files, and apply the same fix to the other
broken entries referenced later in the file (the entry around the single-file
link at line ~95 and the block around lines ~140-145) to ensure all links
resolve from this document.

### 2. Frontend React Application (`frontend/`)

The React application runs in the Electron renderer process:

**Structure:**

```
frontend/
├── app/ # Main application code
│ ├── app.tsx # Root App component
│ ├── aipanel/ # AI panel UI
│ ├── block/ # Block-based UI components
│ ├── element/ # Reusable UI elements
│ ├── hook/ # Custom React hooks
│ ├── modals/ # Modal components
│ ├── store/ # State management (Jotai)
│ ├── tab/ # Tab components
│ ├── view/ # Different view types
│ │ ├── codeeditor/ # Code editor (Monaco)
│ │ ├── preview/ # File preview
│ │ ├── sysinfo/ # System info view
│ │ ├── term/ # Terminal view
│ │ ├── tsunami/ # Tsunami builder view
│ │ ├── vdom/ # Virtual DOM view
│ │ ├── waveai/ # AI chat integration
│ │ ├── waveconfig/ # Config editor view
│ │ └── webview/ # Web view
│ └── workspace/ # Workspace management
├── builder/ # Builder app entry
├── layout/ # Layout system
├── preview/ # Standalone preview renderer
├── types/ # TypeScript type definitions
└── util/ # Utility functions
```

**Key Technologies:**

- Electron (desktop application shell)
- React 19 with TypeScript
- Jotai for state management
- Monaco Editor for code editing
- XTerm.js for terminal emulation
- Tailwind CSS v4 for styling
- SCSS for additional styling (deprecated, new components should use Tailwind)
- Vite / electron-vite for bundling
- Task (Taskfile.yml) for build and code generation commands

### 3. Go Backend Server (`cmd/server/`)

The Go backend server handles all heavy lifting operations:

**Entry Point:** [`main-server.go`](cmd/server/main-server.go)

### 4. Go Packages (`pkg/`)

The Go codebase is organized into modular packages:

**Key Packages:**

- `wstore/` - Database and storage layer
- `wconfig/` - Configuration management
- `wcore/` - Core business logic
- `wshrpc/` - RPC communication system
- `wshutil/` - WSH (Wave Shell) utilities
- `blockcontroller/` - Block execution management
- `remote/` - Remote connection handling
- `filestore/` - File storage system
- `web/` - Web server and WebSocket handling
- `telemetry/` - Usage analytics and telemetry
- `waveobj/` - Core data objects
- `service/` - Service layer
- `wps/` - Wave PubSub event system
- `waveai/` - AI functionality
- `shellexec/` - Shell execution
- `util/` - Common utilities

### 5. Command Line Tools (`cmd/`)

Key Go command-line utilities:

- `wsh/` - Wave Shell command-line tool
- `server/` - Main backend server
- `generatego/` - Code generation
- `generateschema/` - Schema generation
- `generatets/` - TypeScript generation

## Communication Architecture

The core communication system is built around the **WSH RPC (Wave Shell RPC)** system, which provides a unified interface for all inter-process communication: frontend ↔ Go backend, Electron main process ↔ backend, and backend ↔ remote systems (SSH, WSL).

### WSH RPC System (`pkg/wshrpc/`)

The WSH RPC system is the backbone of Wave Terminal's communication architecture:

**Key Components:**

- [`wshrpctypes.go`](pkg/wshrpc/wshrpctypes.go) - Core RPC interface and type definitions (source of truth for all RPC commands)
- [`wshserver/`](pkg/wshrpc/wshserver/) - Server-side RPC implementation
- [`wshremote/`](pkg/wshrpc/wshremote/) - Remote connection handling
- [`wshclient.go`](pkg/wshrpc/wshclient.go) - Go client for making RPC calls
- [`frontend/app/store/wshclientapi.ts`](frontend/app/store/wshclientapi.ts) - Generated TypeScript RPC client

**Routing:** Callers address RPC calls using _routes_ (e.g. a block ID, connection name, or `"waveapp"`) rather than caring about the underlying transport. The RPC layer resolves the route to the correct transport (WebSocket, Unix socket, SSH tunnel, stdio) automatically. This means the same RPC interface works whether the target is local or a remote SSH connection.

## Development Notes

- **Build commands** - Use `task` (Taskfile.yml) for all build, generate, and packaging commands
- **Code generation** - Run `task generate` after modifying Go types in `pkg/wshrpc/wshrpctypes.go`, `pkg/wconfig/settingsconfig.go`, or `pkg/waveobj/wtypemeta.go`
- **Testing** - Vitest for frontend unit tests; standard `go test` for Go packages
- **Database migrations** - SQL migration files in `db/migrations-wstore/` and `db/migrations-filestore/`
- **Documentation** - Docusaurus site in `docs/`
205 changes: 205 additions & 0 deletions .kilocode/rules/rules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
Wave Terminal is a modern terminal which provides graphical blocks, dynamic layout, workspaces, and SSH connection management. It is cross platform and built on electron.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix typo/grammar issues in contributor rules text.

There are a few wording mistakes that can confuse readers (e.g., “cross platform”, “fo”, “react”, “overn”).

✏️ Suggested edits
-Wave Terminal is a modern terminal which provides graphical blocks, dynamic layout, workspaces, and SSH connection management. It is cross platform and built on electron.
+Wave Terminal is a modern terminal which provides graphical blocks, dynamic layout, workspaces, and SSH connection management. It is cross-platform and built on Electron.
...
-  - in general const decls go at the top fo the file (before types and functions)
+  - in general const decls go at the top of the file (before types and functions)
...
-- **CRITICAL** - useAtomValue and useAtom are React HOOKS. They cannot be used inline in JSX code, they must appear at the top of a component in the hooks area of the react code.
+- **CRITICAL** - useAtomValue and useAtom are React HOOKS. They cannot be used inline in JSX code, they must appear at the top of a component in the hooks area of the React code.
-- for simple functions, we prefer `if (!cond) { return }; functionality;` pattern overn `if (cond) { functionality }` because it produces less indentation and is easier to follow.
+- for simple functions, we prefer `if (!cond) { return }; functionality;` pattern over `if (cond) { functionality }` because it produces less indentation and is easier to follow.

Also applies to: 14-14, 93-93, 94-94

🧰 Tools
🪛 LanguageTool

[grammar] ~1-~1: Use a hyphen to join words.
Context: ...d SSH connection management. It is cross platform and built on electron. ### Pro...

(QB_NEW_EN_HYPHEN)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.kilocode/rules/rules.md at line 1, Fix the typos and grammar in the
contributor rules text by updating the sentence "Wave Terminal is a modern
terminal which provides graphical blocks, dynamic layout, workspaces, and SSH
connection management. It is cross platform and built on electron." to use
"cross-platform" and capitalize "Electron", and scan the document for the
reported misspellings and casing issues—replace "fo" with "for", lowercase
"react" with "React", and change "overn" to the intended word (e.g., "overnight"
or "over") wherever they appear (notably near the shown sentence and the other
instances referenced).


### Project Structure

It has a TypeScript/React frontend and a Go backend. They talk together over `wshrpc` a custom RPC protocol that is implemented over websocket (and domain sockets).

### Coding Guidelines

- **Go Conventions**:
- Don't use custom enum types in Go. Instead, use string constants (e.g., `const StatusRunning = "running"` rather than creating a custom type like `type Status string`).
- Use string constants for status values, packet types, and other string-based enumerations.
- in Go code, prefer using Printf() vs Println()
- use "Make" as opposed to "New" for struct initialization func names
- in general const decls go at the top of the file (before types and functions)
- NEVER run `go build` (especially in weird sub-package directories). we can tell if everything compiles by seeing there are no problems/errors.
- **Synchronization**:
- Always prefer to use the `lock.Lock(); defer lock.Unlock()` pattern for synchronization if possible
- Avoid inline lock/unlock pairs - instead create helper functions that use the defer pattern
- When accessing shared data structures (maps, slices, etc.), ensure proper locking
- Example: Instead of `gc.lock.Lock(); gc.map[key]++; gc.lock.Unlock()`, create a helper function like `getNextValue(key string) int { gc.lock.Lock(); defer gc.lock.Unlock(); gc.map[key]++; return gc.map[key] }`
- **TypeScript Imports**:
- Use `@/...` for imports from different parts of the project (configured in `tsconfig.json` as `"@/*": ["frontend/*"]`).
- Prefer relative imports (`"./name"`) only within the same directory.
- Use named exports exclusively; avoid default exports. It's acceptable to export functions directly (e.g., React Components).
- Our indent is 4 spaces
- **JSON Field Naming**: All fields must be lowercase, without underscores.
- **TypeScript Conventions**
- **Type Handling**:
- In TypeScript we have strict null checks off, so no need to add "| null" to all the types.
- In TypeScript for Jotai atoms, if we want to write, we need to type the atom as a PrimitiveAtom<Type>
- Jotai has a bug with strict null checks off where if you create a null atom, e.g. atom(null) it does not "type" correctly. That's no issue, just cast it to the proper PrimitiveAtom type (no "| null") and it will work fine.
- Generally never use "=== undefined" or "!== undefined". This is bad style. Just use a "== null" or "!= null" unless it is a very specific case where we need to distinguish undefined from null.
- **Coding Style**:
- Use all lowercase filenames (except where case is actually important like Taskfile.yml)
- Import the "cn" function from "@/util/util" to do classname / clsx class merge (it uses twMerge underneath)
- For element variants use class-variance-authority
- Do NOT create private fields in classes (they are impossible to inspect)
- Use PascalCase for global consts at the top of files
- **Component Practices**:
- Make sure to add cursor-pointer to buttons/links and clickable items
- NEVER use cursor-help (it looks terrible)
- useAtom() and useAtomValue() are react HOOKS, so they must be called at the component level not inline in JSX
- If you use React.memo(), make sure to add a displayName for the component
- Other
- never use atob() or btoa() (not UTF-8 safe). use functions in frontend/util/util.ts for base64 decoding and encoding
- In general, when writing functions, we prefer _early returns_ rather than putting the majority of a function inside of an if block.

### Styling

- We use **Tailwind v4** to style. Custom stuff is defined in frontend/tailwindsetup.css
- _never_ use cursor-help, or cursor-not-allowed (it looks terrible)
- We have custom CSS setup as well, so it is a hybrid system. For new code we prefer tailwind, and are working to migrate code to all use tailwind.
- For accent buttons, use "bg-accent/80 text-primary rounded hover:bg-accent transition-colors cursor-pointer" (if you do "bg-accent hover:bg-accent/80" it looks weird as on hover the button gets darker instead of lighter)

### RPC System

To define a new RPC call, add the new definition to `pkg/wshrpc/wshrpctypes.go` including any input/output data that is required. After modifying wshrpctypes.go run `task generate` to generate the client APIs.

For normal "server" RPCs (where a frontend client is calling the main server) you should implement the RPC call in `pkg/wshrpc/wshserver.go`.

### Electron API

From within the FE to get the electron API (e.g. the preload functions):

```ts
import { getApi } from "@/store/global";

getApi().getIsDev();
```

The full API is defined in custom.d.ts as type ElectronApi.

### Code Generation

- **TypeScript Types**: TypeScript types are automatically generated from Go types. After modifying Go types in `pkg/wshrpc/wshrpctypes.go`, run `task generate` to update the TypeScript type definitions in `frontend/types/gotypes.d.ts`.
- **Manual Edits**: Do not manually edit generated files like `frontend/types/gotypes.d.ts` or `frontend/app/store/wshclientapi.ts`. Instead, modify the source Go types and run `task generate`.

### Frontend Architecture

- The application uses Jotai for state management.
- When working with Jotai atoms that need to be updated, define them as `PrimitiveAtom<Type>` rather than just `atom<Type>`.

### Notes

- **CRITICAL: Completion format MUST be: "Done: [one-line description]"**
- **Keep your Task Completed summaries VERY short**
- **No lengthy pre-completion summaries** - Do not provide detailed explanations of implementation before using attempt_completion
- **No recaps of changes** - Skip explaining what was done before completion
- **Go directly to completion** - After making changes, proceed directly to attempt_completion without summarizing
- The project is currently an un-released POC / MVP. Do not worry about backward compatibility when making changes
- With React hooks, always complete all hook calls at the top level before any conditional returns (including jotai hook calls useAtom and useAtomValue); when a user explicitly tells you a function handles null inputs, trust them and stop trying to "protect" it with unnecessary checks or workarounds.
- **Match response length to question complexity** - For simple, direct questions in Ask mode (especially those that can be answered in 1-2 sentences), provide equally brief answers. Save detailed explanations for complex topics or when explicitly requested.
- **CRITICAL** - useAtomValue and useAtom are React HOOKS. They cannot be used inline in JSX code, they must appear at the top of a component in the hooks area of the react code.
- for simple functions, we prefer `if (!cond) { return }; functionality;` pattern over `if (cond) { functionality }` because it produces less indentation and is easier to follow.
- It is now 2026, so if you write new files, or update files use 2026 for the copyright year
- React.MutableRefObject is deprecated, just use React.RefObject now (in React 19 RefObject is always mutable)

### Strict Comment Rules

- **NEVER add comments that merely describe what code is doing**:
- ❌ `mutex.Lock() // Lock the mutex`
- ❌ `counter++ // Increment the counter`
- ❌ `buffer.Write(data) // Write data to buffer`
- ❌ `// Header component for app run list` (above AppRunListHeader)
- ❌ `// Updated function to include onClick parameter`
- ❌ `// Changed padding calculation`
- ❌ `// Removed unnecessary div`
- ❌ `// Using the model's width value here`
- **Only use comments for**:
- Explaining WHY a particular approach was chosen
- Documenting non-obvious edge cases or side effects
- Warning about potential pitfalls in usage
- Explaining complex algorithms that can't be simplified
- **When in doubt, leave it out**. No comment is better than a redundant comment.
- **Never add comments explaining code changes** - The code should speak for itself, and version control tracks changes. The one exception to this rule is if it is a very unobvious implementation. Something that someone would typically implement in a different (wrong) way. Then the comment helps us remember WHY we changed it to a less obvious implementation.
- **Never remove existing comments** unless specifically directed by the user. Comments that are already defined in existing code have been vetted by the user.

### Jotai Model Pattern (our rules)

- **Atoms live on the model.**
- **Simple atoms:** define as **field initializers**.
- **Atoms that depend on values/other atoms:** create in the **constructor**.
- Models **never use React hooks**; they use `globalStore.get/set`.
- It's fine to call model methods from **event handlers** or **`useEffect`**.
- Models use the **singleton pattern** with a `private static instance` field, a `private constructor`, and a `static getInstance()` method.
- The constructor is `private`; callers always use `getInstance()`.

```ts
// model/MyModel.ts
import * as jotai from "jotai";
import { globalStore } from "@/app/store/jotaiStore";

export class MyModel {
private static instance: MyModel | null = null;

// simple atoms (field init)
statusAtom = jotai.atom<"idle" | "running" | "error">("idle");
outputAtom = jotai.atom("");

// ctor-built atoms (need types)
lengthAtom!: jotai.Atom<number>;
thresholdedAtom!: jotai.Atom<boolean>;

private constructor(initialThreshold = 20) {
this.lengthAtom = jotai.atom((get) => get(this.outputAtom).length);
this.thresholdedAtom = jotai.atom((get) => get(this.lengthAtom) > initialThreshold);
}

static getInstance(): MyModel {
if (!MyModel.instance) {
MyModel.instance = new MyModel();
}
return MyModel.instance;
}

static resetInstance(): void {
MyModel.instance = null;
}

async doWork() {
globalStore.set(this.statusAtom, "running");
// ... do work ...
globalStore.set(this.statusAtom, "idle");
}
}
```

```tsx
// component usage (events & effects OK)
import { useAtomValue } from "jotai";

function Panel() {
const model = MyModel.getInstance();
const status = useAtomValue(model.statusAtom);
const isBig = useAtomValue(model.thresholdedAtom);

const onClick = () => model.doWork();

return (
<div>
{status} • {String(isBig)}
</div>
);
}
```

**Remember:** singleton pattern with `getInstance()`, `private constructor`, atoms on the model, simple-as-fields, ctor for dependent/derived, updates via `globalStore.set/get`.
**Note** Older models may not use the singleton pattern

### Tool Use

Do NOT use write_to_file unless it is a new file or very short. Always prefer to use replace_in_file. Often your diffs fail when a file may be out of date in your cache vs the actual on-disk format. You should RE-READ the file and try to create diffs again if your diffs fail rather than fall back to write_to_file. If you feel like your ONLY option is to use write_to_file please ask first.

Also when adding content to the end of files prefer to use the new append_file tool rather than trying to create a diff (as your diffs are often not specific enough and end up inserting code in the middle of existing functions).

### Directory Awareness

- **ALWAYS verify the current working directory before executing commands**
- Either run "pwd" first to verify the directory, or do a "cd" to the correct absolute directory before running commands
- When running tests, do not "cd" to the pkg directory and then run the test. This screws up the cwd and you never recover. run the test from the project root instead.

### Testing / Compiling Go Code

No need to run a `go build` or a `go run` to just check if the Go code compiles. VSCode's errors/problems cover this well.
If there are no Go errors in VSCode you can assume the code compiles fine.
Loading
Loading