> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/pingdotgg/t3code/llms.txt
> Use this file to discover all available pages before exploring further.

# WebSocket Protocol

> Learn about the T3 Code WebSocket protocol for real-time communication

## Overview

The T3 Code WebSocket API provides real-time communication between the web client and the Node.js server. The protocol uses a JSON-RPC-style request/response pattern with additional push events for server-initiated updates.

## Connection

Connect to the WebSocket server at the configured port (default: 3773):

```typescript theme={null}
const ws = new WebSocket('ws://localhost:3773');
```

### Authentication

If an auth token is configured, include it as a query parameter:

```typescript theme={null}
const ws = new WebSocket('ws://localhost:3773?token=your-auth-token');
```

## Message Format

### Request/Response Pattern

All client-initiated requests follow this structure:

<ParamField path="id" type="string" required>
  Unique request identifier for matching responses
</ParamField>

<ParamField path="body" type="object" required>
  Request body containing the method tag and parameters
</ParamField>

<ParamField path="body._tag" type="string" required>
  Method name identifier (e.g., `"orchestration.dispatchCommand"`)
</ParamField>

#### Request Example

```json theme={null}
{
  "id": "req-123",
  "body": {
    "_tag": "orchestration.getSnapshot"
  }
}
```

### Response Format

The server responds with either a success or error result:

<ResponseField name="id" type="string" required>
  Matches the request ID
</ResponseField>

<ResponseField name="result" type="unknown">
  The successful result data (present on success)
</ResponseField>

<ResponseField name="error" type="object">
  Error details (present on failure)

  <Expandable title="Error structure">
    <ResponseField name="message" type="string">
      Human-readable error message
    </ResponseField>
  </Expandable>
</ResponseField>

#### Success Response Example

```json theme={null}
{
  "id": "req-123",
  "result": {
    "snapshotSequence": 42,
    "projects": [...],
    "threads": [...],
    "updatedAt": "2026-03-07T12:00:00.000Z"
  }
}
```

#### Error Response Example

```json theme={null}
{
  "id": "req-123",
  "error": {
    "message": "Thread not found"
  }
}
```

## Push Events

The server sends push events without a corresponding request. Push events are used for real-time updates:

<ResponseField name="type" type="literal" default="push">
  Always `"push"` for server-initiated messages
</ResponseField>

<ResponseField name="channel" type="string" required>
  Event channel name (e.g., `"orchestration.domainEvent"`)
</ResponseField>

<ResponseField name="data" type="unknown" required>
  Event payload specific to the channel
</ResponseField>

### Push Event Example

```json theme={null}
{
  "type": "push",
  "channel": "orchestration.domainEvent",
  "data": {
    "sequence": 43,
    "eventId": "evt-456",
    "type": "thread.created",
    "payload": {
      "threadId": "thread-123",
      "projectId": "project-456",
      "title": "New thread",
      "model": "gpt-5.4",
      "createdAt": "2026-03-07T12:00:00.000Z"
    }
  }
}
```

## Available Methods

The T3 Code WebSocket API exposes the following method namespaces:

### Orchestration Methods

Core orchestration and command dispatch:

* `orchestration.getSnapshot` - Get current read model snapshot
* `orchestration.dispatchCommand` - Dispatch a client command
* `orchestration.getTurnDiff` - Get diff for a turn range
* `orchestration.getFullThreadDiff` - Get full thread diff
* `orchestration.replayEvents` - Replay events from a sequence

See [Orchestration API](/api/orchestration) for detailed documentation.

### Project Methods

Project and file operations:

* `projects.list` - List all projects
* `projects.add` - Add a new project
* `projects.remove` - Remove a project
* `projects.searchEntries` - Search project files/directories
* `projects.writeFile` - Write content to a file

### Git Methods

Version control operations:

* `git.status` - Get repository status
* `git.pull` - Pull changes from remote
* `git.listBranches` - List all branches
* `git.createBranch` - Create a new branch
* `git.checkout` - Switch branches
* `git.init` - Initialize a new repository
* `git.createWorktree` - Create a git worktree
* `git.removeWorktree` - Remove a worktree
* `git.runStackedAction` - Execute stacked git operations (commit, push, PR)

See [Git Workflow](/guides/git-workflow) for usage examples.

### Terminal Methods

Interactive terminal sessions:

* `terminal.open` - Open a new terminal session
* `terminal.write` - Write input to terminal
* `terminal.resize` - Resize terminal dimensions
* `terminal.clear` - Clear terminal output
* `terminal.restart` - Restart a terminal session
* `terminal.close` - Close terminal session

### Shell Methods

System integration:

* `shell.openInEditor` - Open directory in external editor

### Server Methods

Server configuration and metadata:

* `server.getConfig` - Get server configuration
* `server.upsertKeybinding` - Update keybinding configuration

<Note>
  All methods are defined in `packages/contracts/src/ws.ts` and follow the request/response pattern described above.
</Note>

## Available Channels

<ParamField path="orchestration.domainEvent" type="channel">
  Real-time orchestration events (project/thread/session updates)

  See [Events](/api/events) for detailed event types.
</ParamField>

<ParamField path="terminal.event" type="channel">
  Terminal session output and state changes
</ParamField>

<ParamField path="server.welcome" type="channel">
  Initial server greeting sent on connection

  <Expandable title="Welcome payload">
    <ResponseField name="cwd" type="string">
      Current working directory
    </ResponseField>

    <ResponseField name="projectName" type="string">
      Inferred project name from directory
    </ResponseField>

    <ResponseField name="bootstrapProjectId" type="string">
      Auto-created project ID (if configured)
    </ResponseField>

    <ResponseField name="bootstrapThreadId" type="string">
      Auto-created thread ID (if configured)
    </ResponseField>
  </Expandable>
</ParamField>

<ParamField path="server.configUpdated" type="channel">
  Server configuration changes (keybindings, provider status)
</ParamField>

## Protocol Schema

The WebSocket protocol is defined using Effect Schema in `@t3tools/contracts`:

```typescript theme={null}
// Source: packages/contracts/src/ws.ts

export const WebSocketRequest = Schema.Struct({
  id: TrimmedNonEmptyString,
  body: WebSocketRequestBody,
});

export const WebSocketResponse = Schema.Struct({
  id: TrimmedNonEmptyString,
  result: Schema.optional(Schema.Unknown),
  error: Schema.optional(
    Schema.Struct({
      message: Schema.String,
    }),
  ),
});

export const WsPush = Schema.Struct({
  type: Schema.Literal("push"),
  channel: TrimmedNonEmptyString,
  data: Schema.Unknown,
});
```

## Implementation Reference

The WebSocket server implementation can be found in:

* **Server**: `apps/server/src/wsServer.ts:544-968`
* **Contracts**: `packages/contracts/src/ws.ts`
* **Client Integration**: `apps/web/src/api/wsClient.ts`

## Best Practices

<Card title="Generate Unique IDs" icon="hashtag">
  Use UUIDs or monotonic counters for request IDs to avoid collisions
</Card>

<Card title="Handle Connection Loss" icon="plug">
  Implement reconnection logic with exponential backoff
</Card>

<Card title="Validate Schemas" icon="shield-check">
  Use Effect Schema for runtime validation of all messages
</Card>

<Card title="Subscribe to Push Events" icon="bell">
  Listen for push events immediately after connection to avoid missing updates
</Card>

## Error Handling

Common error scenarios:

| Error                  | Cause                              | Solution                                 |
| ---------------------- | ---------------------------------- | ---------------------------------------- |
| Invalid request format | Malformed JSON or schema violation | Validate against WebSocketRequest schema |
| Unknown method         | Method name not recognized         | Check available methods in WS\_METHODS   |
| Unauthorized           | Missing or invalid auth token      | Include valid token in connection URL    |
| Route request error    | Business logic failure             | Check error.message for details          |

## Next Steps

<CardGroup cols={2}>
  <Card title="Orchestration API" icon="diagram-project" href="/api/orchestration">
    Learn about orchestration commands and queries
  </Card>

  <Card title="Commands" icon="terminal" href="/api/commands">
    Explore available command types
  </Card>

  <Card title="Events" icon="bolt" href="/api/events">
    Understand domain events
  </Card>
</CardGroup>
