Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python
26.4 KB
Raw Blame

Project & Session Management (Web)

Implementation: jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py (handler registration), jiuwenswarm/gateway/channel_manager/web/git_ws_handler.py (Git Diff WebSocket), jiuwenswarm/server/runtime/session/project_store.py (project storage), jiuwenswarm/server/runtime/session/session_metadata.py (session metadata), jiuwenswarm/server/runtime/session/project_git.py (Git operations), jiuwenswarm/server/runtime/session/git_diff_status.py (Diff aggregation), jiuwenswarm/server/runtime/session/git_diff_watcher.py (Diff monitoring) 中文版: ../zh/项目与会话管理.md


1. Overview

The Web channel provides project-scoped session management. Sessions bind to projects through project_id, and can also fall back to mode-specific default projects.

The current implementation adds a work_mode dimension to isolate regular work collaboration from code projects. code projects support Git status, branch operations, Diff snapshots, live Diff monitoring, and discarding/redoing the last turn's file changes. work projects keep the regular project/session behavior.

Core Concepts

Concept Description
Default projects Not persisted; dynamically injected by APIs. default is the work default project, default_code is the code default project. Rename/remove/pin are forbidden
work_mode Isolation dimension for projects, sessions, and scheduled tasks. Values: work / code. Web defaults to work; TUI defaults to code
Code project Git capabilities Real code projects expose Git status, init, branch, Diff, history, monitoring, and discard/redo APIs. Default projects and work projects do not expose Git operations
Soft delete project.remove marks hidden:true without deleting the record. While hidden, its non-pinned sessions temporarily fall back to the mode-specific default project
Pinned sessions Detached from project groups and fetched via project.pinned_sessions, sorted by pin_order ascending
Pinned projects Pinned projects appear first, sorted by pin_order ascending
Immutability Once project_id, project_dir, and work_mode are bound to a session, they cannot be changed; no cross-project/cross-mode migration API is provided

Communication Convention

  • Transport: WebSocket JSON messages
  • Request structure: { "id": "<req_id>", "method": "<method_name>", "params": { ... } }
  • Response envelope:
Field Type Required Description
ok boolean yes Success flag
payload object on success Response data
error string on failure Error message
code string on failure Error code

session_id Generation

  • session_id is generated by the frontend: sess_<hex millisecond timestamp>_<6-char hex random>
  • The sess_ prefix is a Web convention: only these sessions support history.get recovery
  • The backend does not validate the format, but the frontend must follow it

2. Data Structures

ProjectInfo

Returned by project.list.

Field Type Description
project_id string Unique project ID; defaults are default / default_code
name string Display name
project_dir string Absolute working directory; default projects use ""
pinned boolean Whether pinned
pin_order integer Pin order; lower comes first; 0 when not pinned
is_default boolean Whether this is a default project
hidden boolean Whether soft-deleted; defaults are always false
session_count integer Number of non-pinned sessions in this project
last_message_at number | null Latest message timestamp (UTC seconds)
last_user_message_at number | null Latest user message timestamp; falls back to created_at
created_at number Creation timestamp; defaults use 0
updated_at number Update timestamp; defaults use 0
work_mode string work or code
git object Git snapshot. Written by Git probe/operations for code projects; disabled/empty for work/default projects

GitStatus

Used by ProjectInfo.git and Git status-style responses.

Field Type Description
enabled boolean Whether Git capability is enabled in the persisted snapshot
status string Probe state, such as ready, not_git, git_missing, transient, error, or disabled
repo_root string | null Git repository root
branch string | null Current branch; may be a short HEAD in detached mode
head string | null Short HEAD hash
is_dirty boolean Whether the worktree has changes
error object | null Structured Git error with code, message, hint, etc.

SessionInfo

Returned by project.get_sessions / project.pinned_sessions.

Field Type Description
session_id string Unique session ID
title string Session title
created_at number Creation timestamp
last_message_at number Last message timestamp
message_count integer Message count
mode string Session mode
pinned boolean Whether pinned
pin_order integer Pin order; 0 when not pinned
project_id string Bound project ID; empty string means default
project_dir string Bound project path; empty string means default
work_mode string work or code
last_user_message_at number | null Last user message timestamp; falls back to created_at
model string Current model identifier; empty when unset

Mode Values

Value Description
agent.plan Agent planning mode
agent.fast Agent fast mode
code.plan Code planning mode
code.normal Code normal mode
code.team Code team mode
team Team mode

3. Sorting Rules

Scenario Rule
Pinned sessions (project.pinned_sessions) Sorted by pin_order ascending and detached from project groups
Project list (project.list) Pinned projects first, then by last_user_message_at descending, with default projects at the end
Sessions in a project (project.get_sessions) Non-pinned only, sorted by last_user_message_at descending

session_count and project.get_sessions count only non-pinned sessions. Pinned sessions are returned independently by project.pinned_sessions.


4. Session Interfaces

session.list - List sessions

Flat paginated session list.

Request params:

Param Type Required Description
limit integer no Return limit, default 20, max 200
offset integer no Offset, default 0

Response payload:

Field Type Description
sessions object[] Full session metadata list, including work_mode
total integer Total session count
limit integer Actual limit
offset integer Actual offset
has_more boolean Whether more sessions exist

session.create - Create session

Adds optional project_dir, project_id, and work_mode. When omitted, behavior remains backward compatible. Web defaults to work; TUI defaults to code.

Request params:

Param Type Required Description
session_id string yes Session ID generated by the frontend
title string no Session title
mode string no Mode; default unknown, overwritten by the first chat.send
project_dir string no Absolute working directory. Cannot be supplied alone; must accompany a valid real project_id, or be auto-filled from that project
project_id string no Target project ID. Empty/default project IDs mean the mode-specific default project. Real IDs must point to visible projects
work_mode string no work / code. Must match the target project if project_id is real

Response payload:

Field Type Description
session_id string Created session ID
project_id string Final project binding
project_dir string Final project directory
work_mode string Final work mode

Error codes: BAD_REQUEST, ALREADY_EXISTS, NOT_FOUND


session.delete - Delete session

Deletes the session directory and runtime state.

Request params: session_id (string, required)

Response payload: { "session_id": "<deleted session id>" }

Error codes: NOT_FOUND


session.rename - Rename session

Supports query / set / clear semantics.

Request params:

Param Type Required Description
session_id string yes Target session ID
title string no Omitted/null queries; empty clears; non-empty sets, truncated to 200 chars

Response payload: session_id, title, previous_title.

Error codes: BAD_REQUEST


session.pin - Pin/unpin session

Pinned sessions are detached from project groups into the global pinned area. Pin order is compacted after each operation.

Request params: session_id (string, required), pinned (boolean, required)

Response payload: pinned, pin_order.

Error codes: NOT_FOUND


5. Project Interfaces

project.list - List projects

Returns sorted projects with statistics and injected default projects.

Request params:

Param Type Required Description
filter string no all / pinned / unpinned, default all
include_hidden boolean no Whether to include soft-deleted projects
work_mode string no Filter by work / code; omitted returns all modes

Response payload: projects (ProjectInfo[]).


project.get_sessions - List sessions in a project

Returns non-pinned sessions for a project. default returns unbound/fallback work sessions; default_code returns unbound/fallback code sessions.

Request params: project_id (string, required), optional limit, offset.

Response payload: sessions (SessionInfo[]), total.

Error codes: NOT_FOUND


project.create - Create project

Creates a project with an optional directory. If a non-empty project_dir matches a hidden project in the same work_mode, that project is restored. Code projects automatically probe or initialize Git.

Request params:

Param Type Required Description
name string yes Display name; unique within the same work_mode, including hidden projects
project_dir string no Absolute directory; empty path projects are allowed
work_mode string no work / code; inferred from channel when omitted

Response payload:

Field Type Description
project_id string New or restored project ID
project_dir string Project path
restored boolean Whether a hidden project was restored
project ProjectInfo Full project object
work_mode string Project work mode
git object Git snapshot for code projects; disabled/empty for work projects

Error codes: BAD_REQUEST, CONFLICT


project.rename - Rename project

Renames the display name only. Name conflicts are checked within the same work_mode, including hidden projects.

Request params: project_id (string, required), name (string, required)

Response payload: empty object.

Error codes: BAD_REQUEST, NOT_FOUND, FORBIDDEN, CONFLICT


project.pin - Pin/unpin project

Toggles project pin state and compacts pin order.

Request params: project_id (string, required), pinned (boolean, required)

Response payload: pinned, pin_order.

Error codes: NOT_FOUND, FORBIDDEN


project.remove - Soft-delete project

Marks a project as hidden and unpins it. Its non-pinned sessions temporarily fall back to the mode-specific default project.

Request params: project_id (string, required)

Response payload: affected_sessions.

Error codes: NOT_FOUND, FORBIDDEN


project.restore - Restore project

Restores a hidden project. Sessions automatically reattach by project_id.

Request params: project_id (string, required)

Response payload: affected_sessions.

Error codes: NOT_FOUND, CONFLICT, FORBIDDEN


project.pinned_sessions - List pinned sessions

Returns all pinned sessions sorted by pin_order.

Request params: none

Response payload: sessions (SessionInfo[]).


6. Git & Diff Interfaces (Code Projects)

These methods use the regular /ws request envelope. They are only available for real work_mode="code" projects.

GitStatusPayload

Field Type Description
project_id string Project ID
project_name string Project display name
project_dir string Project working directory
work_mode string Always code
repo object is_git, repo_root, branch, head, detached, transient, upstream
working_tree object is_dirty, staged, unstaged, untracked, conflicted
branches object current, locals, remotes
generated_at number Generation timestamp

project.git.status reads the live worktree without persisting or waking watchers. project.git.probe re-detects Git state, persists ProjectInfo.git, and wakes /ws/git watchers.

DiffSummary / DiffFileEntry / Hunk

Structure Key fields Description
DiffSummary stats, files Summary stats plus a file map; files is {} when files are not requested
DiffFileEntry file_path, status, change_type, lines_added, lines_removed, is_binary, is_new_file, is_deleted_file, is_untracked, is_large_file, is_truncated, hunks Per-file change entry. hunks is omitted when not requested
Hunk old_start, old_lines, new_start, new_lines, lines A continuous diff block for locating changed lines and context

project.git.status - Query Git status

Live Git status for status bars and branch pickers.

Request params: project_id (string, required)

Response payload: GitStatusPayload.

Error codes: BAD_REQUEST, PROJECT_NOT_FOUND, FORBIDDEN, GIT_NOT_FOUND, NOT_GIT_REPOSITORY


project.git.probe - Re-probe Git and persist snapshot

Re-detects Git state and writes the project git snapshot. Use after external git init, Git installation, or .git removal.

Request params: project_id (string, required)

Response payload: GitStatusPayload.

Error codes: BAD_REQUEST, NOT_FOUND, FORBIDDEN, GIT_NOT_FOUND, NOT_GIT_REPOSITORY


project.git.init - Initialize Git repository

Runs git init, refreshes the project snapshot, and wakes Diff watchers.

Request params: project_id (string, required), optional initial_branch (default main)

Response payload: GitStatusPayload.

Error codes: BAD_REQUEST, NOT_FOUND, FORBIDDEN, GIT_NOT_FOUND, GIT_INIT_FAILED


project.git.switch_branch - Switch branch

Switches to an existing local branch. require_clean=true rejects worktrees with uncommitted changes to tracked files; untracked files do not block the switch.

Request params: project_id, branch, optional require_clean.

Response payload: switched, previous_branch, current_branch, status (GitStatusPayload).

Error codes: BAD_REQUEST, NOT_FOUND, FORBIDDEN, GIT_TRANSIENT_STATE, BRANCH_NOT_FOUND, WORKTREE_DIRTY, CHECKOUT_FAILED


project.git.create_branch - Create branch

Creates a local branch and optionally checks it out.

Request params: project_id, branch, optional checkout (default true), optional start_point.

Response payload: created, checked_out, branch, status (GitStatusPayload).

Error codes: BAD_REQUEST, NOT_FOUND, FORBIDDEN, GIT_TRANSIENT_STATE, BRANCH_EXISTS, START_POINT_NOT_FOUND, CHECKOUT_FAILED


project.git.diff_status - Query current and last-turn Diff

Fetches current worktree Diff and, when session_id is provided, the last agent turn Diff. For live updates, use /ws/git subscriptions.

Request params: project_id, optional session_id, optional include_files, optional include_hunks.

Response payload:

Field Type Description
project_id string Project ID
session_id string | null Requested session
work_mode string Always code
repo object is_git, repo_root, branch, head, transient
current DiffSummary | null Current worktree Diff; may be null when no Git, Git missing, or transient
last_turn DiffSummary | null Last turn Diff; null when no session or no history
generated_at number Generation timestamp

Error codes: BAD_REQUEST, PROJECT_NOT_FOUND, FORBIDDEN, GIT_NOT_FOUND


project.git.turn_diff_list - List historical turn Diffs

Returns paginated historical Diff summaries for a session. The session must belong to the requested project.

Request params: project_id, session_id, optional limit (default 50), optional cursor (default 0).

Response payload: project_id, session_id, repo_root, branch, base_head, turns, cursor, next_cursor, has_more, limit, total.

Error codes: BAD_REQUEST, NOT_FOUND, SESSION_NOT_FOUND, SESSION_NOT_BOUND, PROJECT_SESSION_MISMATCH, GIT_TRANSIENT_STATE


project.git.turn_diff - Query one historical turn Diff

Returns detail for one historical turn. change_set_id takes precedence over turn_index.

Request params: project_id, session_id, optional change_set_id, optional turn_index, optional include_files, optional include_hunks.

Response payload: one turn detail with project_id, session_id, repo context, change_set_id, turn_index, message IDs, stats, and files.

Error codes: BAD_REQUEST, NOT_FOUND, SESSION_NOT_FOUND, SESSION_NOT_BOUND, PROJECT_SESSION_MISMATCH, CHANGE_SET_NOT_FOUND, TURN_DIFF_NOT_FOUND, DIFF_HISTORY_EXPIRED, GIT_TRANSIENT_STATE


7. /ws/git Live Monitoring, Discard & Redo

/ws/git uses the same request/response envelope as /ws, and also pushes live events.

Event Trigger Payload summary
project.git.diff_changed Summary fingerprint changed Project/session/repo/current/last_turn/revision
project.git.diff_files_changed Subscribed file list changed Project/session/source/revision/files; last-turn metadata when source is last_turn
project.git.diff_detail_changed Subscribed hunks changed Project/session/source/revision/files; last-turn metadata when source is last_turn
project.git.error Watcher recomputation failed Project/session/error code/message/detail

project.git.diff_watch - Watch Diff summary

Creates a summary watcher. The initial response contains summary stats only; file maps are empty. Later changes are pushed via project.git.diff_changed.

Request params: project_id, optional session_id, optional scope (summary only), optional include_last_turn (default true).

Response payload: watch_id, scope, snapshot (project_id, session_id, repo, current, last_turn, revision).

Error codes: BAD_REQUEST, NOT_FOUND, FORBIDDEN, Git domain errors


project.git.diff_files_watch - Watch file list

Enables or switches file-list watching on an existing watch_id. Initial response returns files without hunks; later changes are pushed via project.git.diff_files_changed.

Request params: project_id, watch_id, source (current / last_turn), optional session_id.

Response payload: watch_id, files_scope, revision, files (map of path to DiffFileEntry without hunks).

Error codes: BAD_REQUEST, NOT_FOUND, FORBIDDEN, Git domain errors


project.git.diff_detail_watch - Watch file details

Replaces the detail subscription for an existing watcher. Only subscribed file hunk changes are pushed.

Request params: project_id, watch_id, source (current / last_turn), files (string[]), optional session_id.

Response payload: watch_id, detail_scope, revision, files (map of requested path to DiffFileEntry; missing files are null; includes hunks).

Error codes: BAD_REQUEST, NOT_FOUND, FORBIDDEN, Git domain errors


project.git.diff_unwatch - Cancel watch

Releases watcher resources. all removes the whole watcher; files / detail only cancels the child subscription. Missing watch_id is idempotently successful.

Request params: watch_id (required), optional scope (all / files / detail, default all).

Response payload: watch_id, cancelled, scope.

Error codes: BAD_REQUEST


project.git.discard_turn_changes - Discard last turn file changes

Restores the current session's last agent turn file changes to their pre-turn state, or deletes files created in that turn. On full success, session-specific file_ops entries for that turn are soft-deleted (marked discarded_out rather than physically removed, preserving snapshots for redo_turn_changes) and Diff watchers are woken. On partial failure, the response uses ok=false and keeps file_ops so the operation can be retried.

Request params: project_id (code project ID), session_id (must belong to the project).

Response payload:

Field Type Description
session_id string Session ID
turn_index integer Discarded last turn index
change_set_id string | null Discarded change set ID; null on partial failure
restored_files string[] Files restored to previous contents
deleted_files string[] Newly created files deleted by discard
errors object[] Per-file restore errors
file_ops_truncated boolean Whether session-specific file_ops entries were marked discarded_out (soft-deleted, preserved for redo)
global_file_ops_truncated boolean Always false; global file_ops are not truncated to avoid cross-session damage
partial boolean Whether the restore partially failed; when true, top-level ok=false and code=PARTIAL_RESTORE_FAILED

Error codes: BAD_REQUEST, NOT_FOUND, FORBIDDEN, SESSION_NOT_BOUND, PROJECT_SESSION_MISMATCH, SESSION_BUSY, NO_TURN_TO_DISCARD, PARTIAL_RESTORE_FAILED


project.git.redo_turn_changes - Redo last turn discarded changes

Symmetric to discard_turn_changes: re-applies the file changes that were discarded by discard_turn_changes to the working directory, restores visibility of file_ops entries (removes discarded_out markers), and clears the turn's discarded status (back to completed). On success, Diff watchers are woken. On partial failure, returns ok=false and keeps the discarded status so the operation can be retried.

Precondition: The last turn must have been discarded (status == "discarded"); otherwise returns NOTHING_TO_REDO.

Request params: project_id (code project ID), session_id (must belong to the project).

Response payload:

Field Type Description
session_id string Session ID
turn_index integer Redone last turn index
change_set_id string | null Restored change set ID; null on partial failure
redone_files string[] Files re-written with agent-modified contents (new_content)
deleted_files string[] Files deleted by the agent (re-deleted on redo)
errors object[] Per-file redo errors
partial boolean Whether the redo partially failed; when true, top-level ok=false and code=PARTIAL_REDO_FAILED

Error codes: BAD_REQUEST, NOT_FOUND, FORBIDDEN, SESSION_NOT_BOUND, PROJECT_SESSION_MISMATCH, SESSION_BUSY, NO_TURN_TO_REDO, NOTHING_TO_REDO, REDO_HISTORY_MISSING, PARTIAL_REDO_FAILED

REDO_HISTORY_MISSING: The last turn is discarded but no redoable file_ops entries were found (file_ops missing/corrupted/no discarded_out markers). The discarded status is preserved for investigation.

NOTHING_TO_REDO: The last turn was not discarded (e.g. status=applied or completed); nothing to redo.


8. Interface Overview

Method Area Description
session.list Session Flat paginated session list
session.create Session Create session with optional project_dir / project_id / work_mode
session.delete Session Delete session
session.rename Session Query/set/clear title
session.pin Session Pin/unpin session
project.list Project List projects with pin and work_mode filters
project.get_sessions Project List non-pinned sessions by project
project.create Project Create/restore project; code projects auto probe/init Git
project.rename Project Rename project
project.pin Project Pin/unpin project
project.remove Project Soft delete project
project.restore Project Restore soft-deleted project
project.pinned_sessions Project List pinned sessions
project.git.status Git Live Git status, not persisted
project.git.probe Git Re-probe Git and persist ProjectInfo.git
project.git.init Git Initialize Git repository
project.git.switch_branch Git Switch branch
project.git.create_branch Git Create branch, optionally checkout
project.git.diff_status Diff Query current and last-turn Diff snapshot
project.git.turn_diff_list Diff List historical turn Diff summaries
project.git.turn_diff Diff Query one historical turn Diff detail
project.git.diff_watch /ws/git Watch Diff summary
project.git.diff_files_watch /ws/git Watch current/last_turn file list
project.git.diff_detail_watch /ws/git Watch selected file hunks
project.git.diff_unwatch /ws/git Cancel watches
project.git.discard_turn_changes /ws/git Discard the current session's last turn code changes
project.git.redo_turn_changes /ws/git Redo the current session's last turn discarded changes