Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
363
crates/luxe-core/src/event/action.rs
Normal file
363
crates/luxe-core/src/event/action.rs
Normal file
@@ -0,0 +1,363 @@
|
||||
//! Action — the UI→core half of the protocol.
|
||||
|
||||
use super::ModelRef;
|
||||
use crate::guided_review::{
|
||||
ReviewId, ReviewLoadRequestId, ReviewRevisionId, ReviewSessionSaveRequestId, ReviewTarget,
|
||||
};
|
||||
use crate::permission::PermissionRequestId;
|
||||
use serde::Serialize;
|
||||
|
||||
mod classify;
|
||||
|
||||
/// UI→core intents — the published wire vocabulary an RPC front-end speaks.
|
||||
///
|
||||
/// Deliberately narrower than [`crate::engine::Action`]. That enum is an implementation detail: it
|
||||
/// carries internal choreography a client must never drive, and payloads (a whole pinned
|
||||
/// `GuidedReview`) no client can hold. This one is a contract, so it moves slowly and every variant
|
||||
/// has to survive being written down in `docs/guide/rpc.md`.
|
||||
///
|
||||
/// `#[non_exhaustive]` plus the [`Action::Other`] fallback make additions non-breaking in both
|
||||
/// directions — an unrecognized variant arrives with its payload preserved verbatim rather than
|
||||
/// failing the parse.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "kind", content = "content", rename_all = "snake_case")]
|
||||
#[non_exhaustive]
|
||||
pub enum Action {
|
||||
// === Conversation ===
|
||||
/// Submit a user message, with any images the front-end collected alongside it.
|
||||
SubmitUserMessage {
|
||||
/// Message text.
|
||||
text: String,
|
||||
/// Base64-encoded attachments for a vision model.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
images: Vec<crate::engine::ImageAttachment>,
|
||||
},
|
||||
/// Deliver `text` to the model at the next checkpoint between tool calls, without ending the
|
||||
/// turn or starting a new one. With no turn in flight it behaves as a plain submission.
|
||||
SteerTurn {
|
||||
/// Message text to deliver mid-turn.
|
||||
text: String,
|
||||
},
|
||||
/// Drop every steer admitted but not yet delivered, so the front-end can hand the text back to
|
||||
/// the user to edit. A steer the model already has stays delivered.
|
||||
WithdrawSteering,
|
||||
Cancel,
|
||||
/// Replace the last user message and re-send it, branching from that message's parent.
|
||||
EditResend {
|
||||
/// Replacement text for the last user message.
|
||||
text: String,
|
||||
},
|
||||
Retry,
|
||||
Regenerate,
|
||||
|
||||
// === Prompts the agent is blocked on ===
|
||||
/// Answer a pending `permission_requested`, matched by `id`.
|
||||
RespondPermission {
|
||||
/// The prompt being answered.
|
||||
id: PermissionRequestId,
|
||||
/// The front-end's decision.
|
||||
reply: crate::permission::PermissionReply,
|
||||
},
|
||||
/// Answer a pending `question_asked`, matched by `id`.
|
||||
AnswerQuestion {
|
||||
/// The question being answered.
|
||||
id: crate::question::QuestionRequestId,
|
||||
/// Chosen options and free text, or a cancellation.
|
||||
reply: crate::question::QuestionReply,
|
||||
},
|
||||
/// Auto-allow permission `ask`s for the rest of the session. `deny` rules still apply.
|
||||
SetPermissionAutoApprove(bool),
|
||||
|
||||
// === Model ===
|
||||
/// Switch the active model. The harness resolves the rest of the metadata from its catalog, so
|
||||
/// a client names a provider and an id and nothing else.
|
||||
SelectModel(ModelRef),
|
||||
/// Set the reasoning level; the turn clamps it to what the active model supports.
|
||||
SetThinkingLevel(crate::provider::ThinkingLevel),
|
||||
/// Switch the session's mode by name (`build`, `plan`). The mode's model and thinking level,
|
||||
/// when it has them, come from config.
|
||||
SetMode(String),
|
||||
/// Ask a reviewer in a fresh context to judge the uncommitted work, answered by
|
||||
/// `review_finished`. `focus` says what to look at hardest.
|
||||
RequestReview {
|
||||
/// What to look at hardest
|
||||
focus: Option<String>,
|
||||
},
|
||||
|
||||
// === Session and workspace ===
|
||||
NewSession,
|
||||
/// Load a specific session by id.
|
||||
LoadSession(String),
|
||||
RefreshSessions,
|
||||
RefreshWorkspace,
|
||||
/// Measure what the next request would carry, answered by `context_composition`.
|
||||
RequestContextComposition,
|
||||
/// Summarize the conversation now, whatever the occupancy, answered by `compaction_done`.
|
||||
///
|
||||
/// Args: `(focus)` — an optional steer for the summary.
|
||||
CompactNow {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
focus: Option<String>,
|
||||
},
|
||||
|
||||
// === Guided Review ===
|
||||
/// Capture one immutable Guided Review source.
|
||||
LoadGuidedReview {
|
||||
/// Correlates loading, loaded, and failed events.
|
||||
request_id: ReviewLoadRequestId,
|
||||
/// Immutable source comparison to capture.
|
||||
target: ReviewTarget,
|
||||
},
|
||||
|
||||
/// Change the open review's comments, answered by `review_session_saved` or
|
||||
/// `review_session_save_failed` under `request_id`. The change is flattened into the payload,
|
||||
/// tagged by `edit`.
|
||||
EditReview {
|
||||
/// Correlates the answer
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
/// The open review
|
||||
review_id: ReviewId,
|
||||
/// What to change
|
||||
#[serde(flatten)]
|
||||
edit: crate::engine::ReviewEdit,
|
||||
},
|
||||
/// Record which chapters of the open review have been read. Saved when it changed, never
|
||||
/// answered.
|
||||
RecordReviewProgress {
|
||||
/// The open review
|
||||
review_id: ReviewId,
|
||||
/// Every chapter walked so far
|
||||
walked_chapter_ids: Vec<crate::guided_review::ChapterId>,
|
||||
},
|
||||
/// Remember what the walked chapters covered, so the next review of the same target leads
|
||||
/// with what is new.
|
||||
RecordReviewSeen {
|
||||
/// The open review
|
||||
review_id: ReviewId,
|
||||
},
|
||||
/// Read the open review again, keeping its comments, if it is still at `revision_id`.
|
||||
RefreshGuidedReview {
|
||||
/// Correlates the loading, loaded and failed events
|
||||
request_id: ReviewLoadRequestId,
|
||||
/// The open review
|
||||
review_id: ReviewId,
|
||||
/// The revision on screen
|
||||
revision_id: ReviewRevisionId,
|
||||
},
|
||||
/// Commit the open review's change, a commit per chapter or one squashed, answered by
|
||||
/// `review_committed` or `review_commit_failed`. Never pushes; refused under read-only.
|
||||
CommitReviewChapters {
|
||||
/// Correlates the answer
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
/// The open review
|
||||
review_id: ReviewId,
|
||||
/// The revision on screen
|
||||
revision_id: ReviewRevisionId,
|
||||
/// Chapters to commit; absent or empty means all of them
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
chapter_ids: Vec<crate::guided_review::ChapterId>,
|
||||
/// One commit for all of it
|
||||
#[serde(default)]
|
||||
squash: bool,
|
||||
},
|
||||
/// Draft the pull request the open review would open, answered by `pull_request_prepared`.
|
||||
/// Luxe keeps the draft for `open_pull_request`.
|
||||
PreparePullRequest {
|
||||
/// Names the draft
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
/// The open review
|
||||
review_id: ReviewId,
|
||||
},
|
||||
/// Open the drafted pull request with these words, answered by `pull_request_opened` or
|
||||
/// `pull_request_open_failed`. A GitHub write.
|
||||
OpenPullRequest {
|
||||
/// The draft being opened
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
/// Its title
|
||||
title: String,
|
||||
/// Its description
|
||||
body: String,
|
||||
/// Open it as a draft
|
||||
#[serde(default)]
|
||||
draft: bool,
|
||||
},
|
||||
/// Draft the open review as a stack, one pull request per chapter, answered by
|
||||
/// `stack_prepared`. Luxe keeps the layers for `open_stack`.
|
||||
PrepareStack {
|
||||
/// Names the stack
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
/// The open review
|
||||
review_id: ReviewId,
|
||||
},
|
||||
/// Open the drafted stack, answered by `stack_opened`. A GitHub write.
|
||||
OpenStack {
|
||||
/// The stack being opened
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
/// Open every layer as a draft
|
||||
#[serde(default)]
|
||||
draft: bool,
|
||||
},
|
||||
/// Read what posting the open pull request review needs, answered by
|
||||
/// `pull_request_post_prepared`. Luxe keeps it for `post_pull_request_review`.
|
||||
PreparePullRequestPost {
|
||||
/// Names the preview
|
||||
request_id: crate::guided_review::PullRequestPostId,
|
||||
/// The open review
|
||||
review_id: ReviewId,
|
||||
},
|
||||
/// Post the open pull request review with a verdict, answered by `pull_request_review_posted`
|
||||
/// or `pull_request_post_failed`. A GitHub write.
|
||||
PostPullRequestReview {
|
||||
/// The preview being posted
|
||||
request_id: crate::guided_review::PullRequestPostId,
|
||||
/// `comment`, `approve` or `request_changes`
|
||||
verdict: crate::github::ReviewEvent,
|
||||
/// The session revision the preview was drawn from; refused if it moved
|
||||
session_revision: u64,
|
||||
},
|
||||
/// Read whether the fixes behind a thread answer are on GitHub yet, answered by
|
||||
/// `thread_answers_prepared`.
|
||||
PrepareThreadAnswers {
|
||||
/// Correlates the answer
|
||||
request_id: crate::guided_review::ThreadAnswersId,
|
||||
/// The open review of your own pull request
|
||||
review_id: ReviewId,
|
||||
},
|
||||
/// Reply to and resolve threads on your own pull request, answered by `threads_answered`. A
|
||||
/// GitHub write.
|
||||
AnswerThreads {
|
||||
/// Correlates the answer
|
||||
request_id: crate::guided_review::ThreadAnswersId,
|
||||
/// The open review of your own pull request
|
||||
review_id: ReviewId,
|
||||
/// One per thread, named by the comment it became
|
||||
answers: Vec<crate::guided_review::ThreadReply>,
|
||||
},
|
||||
|
||||
// === GitHub ===
|
||||
/// Run `/github`'s searches, answered together by `github_listed`.
|
||||
///
|
||||
/// Args: `(sections)` — each a name and a GitHub search, `{repo}` standing for the checkout's
|
||||
/// repository; absent means the user's configured sections.
|
||||
ListGithub {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
sections: Option<Vec<crate::config::GithubSection>>,
|
||||
},
|
||||
/// Run one search on its own, or its next page, answered by `github_searched`.
|
||||
SearchGithub {
|
||||
/// The client's id for it, echoed in the answer
|
||||
request: u64,
|
||||
/// The search, `{repo}` still in its query
|
||||
section: crate::config::GithubSection,
|
||||
/// The cursor the page starts after; absent for the first page
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
after: Option<String>,
|
||||
},
|
||||
/// Read one pull request's or issue's overview, answered by `github_overview_read`.
|
||||
ReadGithubOverview {
|
||||
/// `owner/name`, when it is not the checkout's repository
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
repository: Option<String>,
|
||||
/// Its number
|
||||
number: u64,
|
||||
/// Whether it is a pull request, rather than an issue
|
||||
pull_request: bool,
|
||||
},
|
||||
/// Read everything said on a pull request or issue, answered by `github_conversation_read`.
|
||||
ReadGithubConversation {
|
||||
/// `owner/name`, when it is not the checkout's repository
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
repository: Option<String>,
|
||||
/// Its number
|
||||
number: u64,
|
||||
/// Whether it is a pull request, rather than an issue
|
||||
pull_request: bool,
|
||||
},
|
||||
/// Have the agent draft a reply in a turn that changes nothing, answered by
|
||||
/// `github_reply_drafted`.
|
||||
DraftGithubReply(crate::engine::DraftRequest),
|
||||
/// Ask whether a pull request can be checked out here to fix, answered by
|
||||
/// `pull_request_fix_checked`.
|
||||
CheckPullRequestFix {
|
||||
/// Its number
|
||||
number: u64,
|
||||
/// `owner/name`, when it is not the checkout's repository
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
repository: Option<String>,
|
||||
},
|
||||
/// Work out what restacking the checked-out branch's stack would do, answered by
|
||||
/// `restack_planned`. Luxe keeps the plan for the `restack` that confirms it.
|
||||
PlanRestack {
|
||||
/// Names the plan
|
||||
request_id: crate::restack::RestackId,
|
||||
},
|
||||
/// Ask what in the session's worktree is not committed, answered by
|
||||
/// `worktree_removal_checked`.
|
||||
CheckWorktreeRemoval,
|
||||
/// Capture one file's change, answered by `file_diff_loaded` or `file_diff_failed`.
|
||||
LoadFileDiff {
|
||||
/// Correlates the answer
|
||||
request_id: crate::file_diff::FileDiffRequestId,
|
||||
/// Project-relative, or an absolute path the session touched outside the project
|
||||
path: String,
|
||||
},
|
||||
/// List one project folder, answered by `directory_listed` or `directory_list_failed`.
|
||||
ListDirectory {
|
||||
/// Correlates the answer
|
||||
request_id: crate::project_files::ListingRequestId,
|
||||
/// Project-relative folder; empty for the project root
|
||||
path: String,
|
||||
/// List what `.gitignore` ignores too, each entry marked; off when absent
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
include_ignored: bool,
|
||||
},
|
||||
/// Read one project file, answered by `project_file_read` or `project_file_read_failed`.
|
||||
ReadProjectFile {
|
||||
/// Correlates the answer
|
||||
request_id: crate::project_files::FileReadRequestId,
|
||||
/// Project-relative file
|
||||
path: String,
|
||||
},
|
||||
/// Whether the client's window has focus, which paces Luxe's background GitHub refreshes.
|
||||
SetFocus {
|
||||
/// Whether it now has focus
|
||||
focused: bool,
|
||||
},
|
||||
/// Record that this session worked on a pull request.
|
||||
LinkPullRequest {
|
||||
/// Its number
|
||||
number: u64,
|
||||
/// Its web address
|
||||
url: String,
|
||||
},
|
||||
/// Post a reply or comment, answered by `github_comment_posted`. A GitHub write.
|
||||
PostGithubComment(crate::engine::GithubPost),
|
||||
/// Update, mark ready, merge, or set auto-merge on a pull request, answered by
|
||||
/// `pull_request_changed`. A GitHub write.
|
||||
ChangePullRequest {
|
||||
/// `owner/name`, when it is not the checkout's repository
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
repository: Option<String>,
|
||||
/// Its number
|
||||
number: u64,
|
||||
/// What to change
|
||||
write: crate::engine::PullRequestWrite,
|
||||
},
|
||||
/// Push the plan `plan_restack` made under `request_id`, answered by `restacked` or
|
||||
/// `restack_failed`. A GitHub write.
|
||||
Restack {
|
||||
/// The plan that was shown
|
||||
request_id: crate::restack::RestackId,
|
||||
},
|
||||
|
||||
// === Lifecycle ===
|
||||
/// Shut the engine down, stopping a turn in flight the way `cancel` does. The event stream
|
||||
/// ends after it.
|
||||
Close,
|
||||
|
||||
/// Catch-all for variants this build does not know about.
|
||||
Other {
|
||||
kind: String,
|
||||
content: serde_json::Value,
|
||||
},
|
||||
}
|
||||
201
crates/luxe-core/src/event/action/classify.rs
Normal file
201
crates/luxe-core/src/event/action/classify.rs
Normal file
@@ -0,0 +1,201 @@
|
||||
//! What an `Action` is called on the wire, and which side of the write lines it falls on.
|
||||
|
||||
use super::Action;
|
||||
|
||||
impl Action {
|
||||
/// The `kind` this action serializes as.
|
||||
///
|
||||
/// A `match` rather than a lookup, so the compiler keeps it complete: adding a variant stops
|
||||
/// this compiling until its kind is written down. `#[non_exhaustive]` binds other crates, not
|
||||
/// this one, which is why the list is published from here — a translator in `luxe-cli` cannot
|
||||
/// match this enum exhaustively even when it covers every variant.
|
||||
pub fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Self::SubmitUserMessage { .. } => "submit_user_message",
|
||||
Self::SteerTurn { .. } => "steer_turn",
|
||||
Self::WithdrawSteering => "withdraw_steering",
|
||||
Self::Cancel => "cancel",
|
||||
Self::EditResend { .. } => "edit_resend",
|
||||
Self::Retry => "retry",
|
||||
Self::Regenerate => "regenerate",
|
||||
Self::RespondPermission { .. } => "respond_permission",
|
||||
Self::AnswerQuestion { .. } => "answer_question",
|
||||
Self::SetPermissionAutoApprove(_) => "set_permission_auto_approve",
|
||||
Self::SelectModel(_) => "select_model",
|
||||
Self::SetThinkingLevel(_) => "set_thinking_level",
|
||||
Self::SetMode(_) => "set_mode",
|
||||
Self::RequestReview { .. } => "request_review",
|
||||
Self::NewSession => "new_session",
|
||||
Self::LoadSession(_) => "load_session",
|
||||
Self::RefreshSessions => "refresh_sessions",
|
||||
Self::RefreshWorkspace => "refresh_workspace",
|
||||
Self::RequestContextComposition => "request_context_composition",
|
||||
Self::CompactNow { .. } => "compact_now",
|
||||
Self::LoadGuidedReview { .. } => "load_guided_review",
|
||||
Self::EditReview { .. } => "edit_review",
|
||||
Self::RecordReviewProgress { .. } => "record_review_progress",
|
||||
Self::RecordReviewSeen { .. } => "record_review_seen",
|
||||
Self::RefreshGuidedReview { .. } => "refresh_guided_review",
|
||||
Self::CommitReviewChapters { .. } => "commit_review_chapters",
|
||||
Self::PreparePullRequest { .. } => "prepare_pull_request",
|
||||
Self::OpenPullRequest { .. } => "open_pull_request",
|
||||
Self::PrepareStack { .. } => "prepare_stack",
|
||||
Self::OpenStack { .. } => "open_stack",
|
||||
Self::PreparePullRequestPost { .. } => "prepare_pull_request_post",
|
||||
Self::PostPullRequestReview { .. } => "post_pull_request_review",
|
||||
Self::PrepareThreadAnswers { .. } => "prepare_thread_answers",
|
||||
Self::AnswerThreads { .. } => "answer_threads",
|
||||
Self::ListGithub { .. } => "list_github",
|
||||
Self::SearchGithub { .. } => "search_github",
|
||||
Self::ReadGithubOverview { .. } => "read_github_overview",
|
||||
Self::ReadGithubConversation { .. } => "read_github_conversation",
|
||||
Self::DraftGithubReply(_) => "draft_github_reply",
|
||||
Self::CheckPullRequestFix { .. } => "check_pull_request_fix",
|
||||
Self::PlanRestack { .. } => "plan_restack",
|
||||
Self::CheckWorktreeRemoval => "check_worktree_removal",
|
||||
Self::LoadFileDiff { .. } => "load_file_diff",
|
||||
Self::ListDirectory { .. } => "list_directory",
|
||||
Self::ReadProjectFile { .. } => "read_project_file",
|
||||
Self::SetFocus { .. } => "set_focus",
|
||||
Self::LinkPullRequest { .. } => "link_pull_request",
|
||||
Self::PostGithubComment(_) => "post_github_comment",
|
||||
Self::ChangePullRequest { .. } => "change_pull_request",
|
||||
Self::Restack { .. } => "restack",
|
||||
Self::Close => "close",
|
||||
// The one variant whose tag is not known until runtime, so it reports the category.
|
||||
// A caller that needs the client's actual string reads it off the variant.
|
||||
Self::Other { .. } => "other",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every `kind` a client may send, `other` excluded.
|
||||
///
|
||||
/// Published so a front-end can advertise what it supports and a translator in another crate
|
||||
/// can be held to the whole list — `#[non_exhaustive]` makes an exhaustive match impossible
|
||||
/// there. `the_published_kind_list_matches_the_variants` keeps it honest against [`Self::kind`].
|
||||
pub const KINDS: &'static [&'static str] = &[
|
||||
"submit_user_message",
|
||||
"steer_turn",
|
||||
"withdraw_steering",
|
||||
"cancel",
|
||||
"edit_resend",
|
||||
"retry",
|
||||
"regenerate",
|
||||
"respond_permission",
|
||||
"answer_question",
|
||||
"set_permission_auto_approve",
|
||||
"select_model",
|
||||
"set_thinking_level",
|
||||
"set_mode",
|
||||
"request_review",
|
||||
"new_session",
|
||||
"load_session",
|
||||
"refresh_sessions",
|
||||
"refresh_workspace",
|
||||
"request_context_composition",
|
||||
"compact_now",
|
||||
"load_guided_review",
|
||||
"edit_review",
|
||||
"record_review_progress",
|
||||
"record_review_seen",
|
||||
"refresh_guided_review",
|
||||
"commit_review_chapters",
|
||||
"prepare_pull_request",
|
||||
"open_pull_request",
|
||||
"prepare_stack",
|
||||
"open_stack",
|
||||
"prepare_pull_request_post",
|
||||
"post_pull_request_review",
|
||||
"prepare_thread_answers",
|
||||
"answer_threads",
|
||||
"list_github",
|
||||
"search_github",
|
||||
"read_github_overview",
|
||||
"read_github_conversation",
|
||||
"draft_github_reply",
|
||||
"check_pull_request_fix",
|
||||
"plan_restack",
|
||||
"check_worktree_removal",
|
||||
"load_file_diff",
|
||||
"list_directory",
|
||||
"read_project_file",
|
||||
"set_focus",
|
||||
"link_pull_request",
|
||||
"post_github_comment",
|
||||
"change_pull_request",
|
||||
"restack",
|
||||
"close",
|
||||
];
|
||||
|
||||
/// Whether this action writes the repository's own history without publishing anything:
|
||||
/// committing a review's chapters.
|
||||
///
|
||||
/// A read-only session refuses it, the way the permission engine refuses the agent's own
|
||||
/// commits there. Every GitHub write commits or pushes too, and is refused there already.
|
||||
pub fn writes_the_repository(&self) -> bool {
|
||||
matches!(self, Self::CommitReviewChapters { .. })
|
||||
}
|
||||
|
||||
/// Whether this action publishes to GitHub: posts, pushes, merges, or changes a pull request.
|
||||
///
|
||||
/// The line `luxe --rpc` draws without `--github-writes`. Every variant is named rather than
|
||||
/// matched by a wildcard, so a new action does not compile until someone has decided which side
|
||||
/// of that line it is on. Reading GitHub, drafting, and planning are not writes; neither is
|
||||
/// recording a pull request on the session, which never leaves the machine.
|
||||
pub fn writes_to_github(&self) -> bool {
|
||||
match self {
|
||||
Self::PostGithubComment(_)
|
||||
| Self::ChangePullRequest { .. }
|
||||
| Self::Restack { .. }
|
||||
| Self::OpenPullRequest { .. }
|
||||
| Self::OpenStack { .. }
|
||||
| Self::PostPullRequestReview { .. }
|
||||
| Self::AnswerThreads { .. } => true,
|
||||
Self::SubmitUserMessage { .. }
|
||||
| Self::SteerTurn { .. }
|
||||
| Self::WithdrawSteering
|
||||
| Self::Cancel
|
||||
| Self::EditResend { .. }
|
||||
| Self::Retry
|
||||
| Self::Regenerate
|
||||
| Self::RespondPermission { .. }
|
||||
| Self::AnswerQuestion { .. }
|
||||
| Self::SetPermissionAutoApprove(_)
|
||||
| Self::SelectModel(_)
|
||||
| Self::SetThinkingLevel(_)
|
||||
| Self::SetMode(_)
|
||||
| Self::RequestReview { .. }
|
||||
| Self::NewSession
|
||||
| Self::LoadSession(_)
|
||||
| Self::RefreshSessions
|
||||
| Self::RefreshWorkspace
|
||||
| Self::RequestContextComposition
|
||||
| Self::CompactNow { .. }
|
||||
| Self::LoadGuidedReview { .. }
|
||||
| Self::EditReview { .. }
|
||||
| Self::RecordReviewProgress { .. }
|
||||
| Self::RecordReviewSeen { .. }
|
||||
| Self::RefreshGuidedReview { .. }
|
||||
| Self::CommitReviewChapters { .. }
|
||||
| Self::PreparePullRequest { .. }
|
||||
| Self::PrepareStack { .. }
|
||||
| Self::PreparePullRequestPost { .. }
|
||||
| Self::PrepareThreadAnswers { .. }
|
||||
| Self::ListGithub { .. }
|
||||
| Self::SearchGithub { .. }
|
||||
| Self::ReadGithubOverview { .. }
|
||||
| Self::ReadGithubConversation { .. }
|
||||
| Self::DraftGithubReply(_)
|
||||
| Self::CheckPullRequestFix { .. }
|
||||
| Self::PlanRestack { .. }
|
||||
| Self::CheckWorktreeRemoval
|
||||
| Self::LoadFileDiff { .. }
|
||||
| Self::ListDirectory { .. }
|
||||
| Self::ReadProjectFile { .. }
|
||||
| Self::SetFocus { .. }
|
||||
| Self::LinkPullRequest { .. }
|
||||
| Self::Close
|
||||
| Self::Other { .. } => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
191
crates/luxe-core/src/event/decode.rs
Normal file
191
crates/luxe-core/src/event/decode.rs
Normal file
@@ -0,0 +1,191 @@
|
||||
//! Decoding — how a frame becomes an `Action` or an `Event`.
|
||||
|
||||
use super::{Action, Event};
|
||||
use serde::de::value::MapDeserializer;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
mod known_action;
|
||||
mod known_event;
|
||||
|
||||
use known_action::KnownAction;
|
||||
use known_event::KnownEvent;
|
||||
|
||||
impl<'de> Deserialize<'de> for Action {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
// `"content":null` lands as `None` here, so an action reads it as no content at all
|
||||
#[derive(Deserialize)]
|
||||
struct Frame {
|
||||
kind: String,
|
||||
content: Option<serde_json::Value>,
|
||||
}
|
||||
let raw = serde_json::Value::deserialize(deserializer)?;
|
||||
let frame = Frame::deserialize(&raw)
|
||||
.map_err(|e| serde::de::Error::custom(format!("action: {e}")))?;
|
||||
decode_frame(frame.kind, frame.content, raw)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Event {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let raw = serde_json::Value::deserialize(deserializer)?;
|
||||
let fields = raw.as_object().ok_or_else(|| serde::de::Error::custom("expected object"))?;
|
||||
let kind = fields
|
||||
.get("kind")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.ok_or_else(|| serde::de::Error::custom("expected string kind"))?
|
||||
.to_string();
|
||||
let content = fields.get("content").cloned();
|
||||
decode_frame(kind, content, raw)
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of a frame decoder serde derives: every known variant, decoded through a mirror enum.
|
||||
///
|
||||
/// The derive cannot express the rest, which [`decode_frame`] adds: an unknown tag becomes `Other`
|
||||
/// with the whole frame kept, and a payload-less frame takes any of the empty forms.
|
||||
trait KnownFrames: Sized {
|
||||
fn decode_known<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>;
|
||||
fn unknown(kind: String, frame: serde_json::Value) -> Self;
|
||||
}
|
||||
|
||||
impl KnownFrames for Action {
|
||||
fn decode_known<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
KnownAction::deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn unknown(kind: String, frame: serde_json::Value) -> Self {
|
||||
Self::Other { kind, content: frame }
|
||||
}
|
||||
}
|
||||
|
||||
impl KnownFrames for Event {
|
||||
fn decode_known<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
KnownEvent::deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn unknown(kind: String, frame: serde_json::Value) -> Self {
|
||||
Self::Other { kind, content: frame }
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes one frame from its tag and content, keeping the whole `frame` for an unknown tag.
|
||||
///
|
||||
/// A payload-less frame may be written `{"kind":"cancel"}`, with `"content":null` or with
|
||||
/// `"content":{}` — refusing two of them would be pedantry a hand-written client trips over — but
|
||||
/// real content on one is a mistake and is named as one. A payload frame with no content reads as
|
||||
/// `{}`, so one whose fields all default can be sent bare. Errors name the frame they came from.
|
||||
fn decode_frame<T, E>(
|
||||
kind: String,
|
||||
content: Option<serde_json::Value>,
|
||||
frame: serde_json::Value,
|
||||
) -> Result<T, E>
|
||||
where
|
||||
T: KnownFrames,
|
||||
E: serde::de::Error,
|
||||
{
|
||||
let empty = content.as_ref().is_none_or(|content| {
|
||||
content.is_null() || content.as_object().is_some_and(serde_json::Map::is_empty)
|
||||
});
|
||||
match T::decode_known(TagOnly::frame(&kind)) {
|
||||
Err(TagOnly::Unknown) => Ok(T::unknown(kind, frame)),
|
||||
Ok(bare) if empty => Ok(bare),
|
||||
// an optional payload decodes bare too, so content is refused only where it cannot decode;
|
||||
// a bad value for one would be named as no content, which no variant here can hit yet
|
||||
Ok(_) => decode_content(&kind, content)
|
||||
.map_err(|_: E| E::custom(format!("{kind} takes no content"))),
|
||||
Err(TagOnly::NeedsContent) => decode_content(&kind, content),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes a known frame's payload, reading no content as `{}`.
|
||||
fn decode_content<T, E>(kind: &str, content: Option<serde_json::Value>) -> Result<T, E>
|
||||
where
|
||||
T: KnownFrames,
|
||||
E: serde::de::Error,
|
||||
{
|
||||
let content = content.unwrap_or_else(|| serde_json::json!({}));
|
||||
T::decode_known(serde_json::json!({ "kind": kind, "content": content }))
|
||||
.map_err(|error| E::custom(format!("{kind}: {error}")))
|
||||
}
|
||||
|
||||
/// What decoding a tag alone says: unknown, or known and wanting content.
|
||||
///
|
||||
/// A typed error rather than a message to match on. Decoding `{"kind": …}` with no content
|
||||
/// succeeds for a payload-less variant, fails through `unknown_variant` for a tag the mirror lacks,
|
||||
/// and fails for want of content otherwise — which is every other error a tag alone can raise.
|
||||
#[derive(Debug)]
|
||||
enum TagOnly {
|
||||
Unknown,
|
||||
NeedsContent,
|
||||
}
|
||||
|
||||
impl TagOnly {
|
||||
fn frame(kind: &str) -> MapDeserializer<'_, std::iter::Once<(&'static str, &str)>, Self> {
|
||||
MapDeserializer::new(std::iter::once(("kind", kind)))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for TagOnly {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Unknown => "unknown tag",
|
||||
Self::NeedsContent => "content required",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TagOnly {}
|
||||
|
||||
impl serde::de::Error for TagOnly {
|
||||
fn custom<T: std::fmt::Display>(_: T) -> Self {
|
||||
Self::NeedsContent
|
||||
}
|
||||
|
||||
fn unknown_variant(_: &str, _: &'static [&'static str]) -> Self {
|
||||
Self::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
#[serde(tag = "kind", content = "content", rename_all = "snake_case")]
|
||||
enum Frames {
|
||||
Bare,
|
||||
Maybe(Option<u32>),
|
||||
}
|
||||
|
||||
impl KnownFrames for Frames {
|
||||
fn decode_known<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
Self::deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn unknown(_: String, _: serde_json::Value) -> Self {
|
||||
unreachable!("every tag here is known")
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(kind: &str, content: Option<serde_json::Value>) -> Result<Frames, serde_json::Error> {
|
||||
decode_frame(kind.into(), content, serde_json::Value::Null)
|
||||
}
|
||||
|
||||
/// An optional payload decodes bare, like a payload-less frame, but its content is not refused.
|
||||
///
|
||||
/// The break this catches: a tag that decodes without content was taken to mean the frame
|
||||
/// takes none, which would refuse every real value of a `Foo(Option<T>)` variant.
|
||||
#[test]
|
||||
fn an_optional_payload_is_read_not_refused() {
|
||||
assert_eq!(decode("maybe", None).unwrap(), Frames::Maybe(None));
|
||||
assert_eq!(decode("maybe", Some(serde_json::json!(3))).unwrap(), Frames::Maybe(Some(3)));
|
||||
let error = decode("bare", Some(serde_json::json!(3))).unwrap_err();
|
||||
assert_eq!(error.to_string(), "bare takes no content");
|
||||
}
|
||||
}
|
||||
190
crates/luxe-core/src/event/decode/known_action.rs
Normal file
190
crates/luxe-core/src/event/decode/known_action.rs
Normal file
@@ -0,0 +1,190 @@
|
||||
//! The mirror of `Action`'s known variants that serde derives a decoder from.
|
||||
|
||||
use super::super::{Action, ModelRef};
|
||||
use crate::guided_review::{
|
||||
ReviewId, ReviewLoadRequestId, ReviewRevisionId, ReviewSessionSaveRequestId, ReviewTarget,
|
||||
};
|
||||
use crate::permission::PermissionRequestId;
|
||||
use serde::Deserialize;
|
||||
|
||||
/// [`Action`]'s known variants, field for field, for serde to derive a decoder from.
|
||||
///
|
||||
/// `remote` makes the derive build `Action` itself, so a field this mirror names wrongly does not
|
||||
/// compile. A variant left out of it decodes as `Other`, which the samples test catches.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(remote = "Action", tag = "kind", content = "content", rename_all = "snake_case")]
|
||||
pub(super) enum KnownAction {
|
||||
SubmitUserMessage {
|
||||
text: String,
|
||||
#[serde(default)]
|
||||
images: Vec<crate::engine::ImageAttachment>,
|
||||
},
|
||||
SteerTurn {
|
||||
text: String,
|
||||
},
|
||||
WithdrawSteering,
|
||||
Cancel,
|
||||
EditResend {
|
||||
text: String,
|
||||
},
|
||||
Retry,
|
||||
Regenerate,
|
||||
RespondPermission {
|
||||
id: PermissionRequestId,
|
||||
reply: crate::permission::PermissionReply,
|
||||
},
|
||||
AnswerQuestion {
|
||||
id: crate::question::QuestionRequestId,
|
||||
reply: crate::question::QuestionReply,
|
||||
},
|
||||
SetPermissionAutoApprove(bool),
|
||||
SelectModel(ModelRef),
|
||||
SetThinkingLevel(crate::provider::ThinkingLevel),
|
||||
SetMode(String),
|
||||
RequestReview {
|
||||
focus: Option<String>,
|
||||
},
|
||||
NewSession,
|
||||
LoadSession(String),
|
||||
RefreshSessions,
|
||||
RefreshWorkspace,
|
||||
RequestContextComposition,
|
||||
CompactNow {
|
||||
#[serde(default)]
|
||||
focus: Option<String>,
|
||||
},
|
||||
LoadGuidedReview {
|
||||
request_id: ReviewLoadRequestId,
|
||||
target: ReviewTarget,
|
||||
},
|
||||
EditReview {
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
review_id: ReviewId,
|
||||
#[serde(flatten)]
|
||||
edit: crate::engine::ReviewEdit,
|
||||
},
|
||||
RecordReviewProgress {
|
||||
review_id: ReviewId,
|
||||
walked_chapter_ids: Vec<crate::guided_review::ChapterId>,
|
||||
},
|
||||
RecordReviewSeen {
|
||||
review_id: ReviewId,
|
||||
},
|
||||
RefreshGuidedReview {
|
||||
request_id: ReviewLoadRequestId,
|
||||
review_id: ReviewId,
|
||||
revision_id: ReviewRevisionId,
|
||||
},
|
||||
CommitReviewChapters {
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
review_id: ReviewId,
|
||||
revision_id: ReviewRevisionId,
|
||||
#[serde(default)]
|
||||
chapter_ids: Vec<crate::guided_review::ChapterId>,
|
||||
#[serde(default)]
|
||||
squash: bool,
|
||||
},
|
||||
PreparePullRequest {
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
review_id: ReviewId,
|
||||
},
|
||||
OpenPullRequest {
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
title: String,
|
||||
body: String,
|
||||
#[serde(default)]
|
||||
draft: bool,
|
||||
},
|
||||
PrepareStack {
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
review_id: ReviewId,
|
||||
},
|
||||
OpenStack {
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
#[serde(default)]
|
||||
draft: bool,
|
||||
},
|
||||
PreparePullRequestPost {
|
||||
request_id: crate::guided_review::PullRequestPostId,
|
||||
review_id: ReviewId,
|
||||
},
|
||||
PostPullRequestReview {
|
||||
request_id: crate::guided_review::PullRequestPostId,
|
||||
verdict: crate::github::ReviewEvent,
|
||||
session_revision: u64,
|
||||
},
|
||||
PrepareThreadAnswers {
|
||||
request_id: crate::guided_review::ThreadAnswersId,
|
||||
review_id: ReviewId,
|
||||
},
|
||||
AnswerThreads {
|
||||
request_id: crate::guided_review::ThreadAnswersId,
|
||||
review_id: ReviewId,
|
||||
answers: Vec<crate::guided_review::ThreadReply>,
|
||||
},
|
||||
ListGithub {
|
||||
#[serde(default)]
|
||||
sections: Option<Vec<crate::config::GithubSection>>,
|
||||
},
|
||||
SearchGithub {
|
||||
request: u64,
|
||||
section: crate::config::GithubSection,
|
||||
#[serde(default)]
|
||||
after: Option<String>,
|
||||
},
|
||||
ReadGithubOverview {
|
||||
#[serde(default)]
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
pull_request: bool,
|
||||
},
|
||||
ReadGithubConversation {
|
||||
#[serde(default)]
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
pull_request: bool,
|
||||
},
|
||||
DraftGithubReply(crate::engine::DraftRequest),
|
||||
CheckPullRequestFix {
|
||||
number: u64,
|
||||
#[serde(default)]
|
||||
repository: Option<String>,
|
||||
},
|
||||
PlanRestack {
|
||||
request_id: crate::restack::RestackId,
|
||||
},
|
||||
CheckWorktreeRemoval,
|
||||
LoadFileDiff {
|
||||
request_id: crate::file_diff::FileDiffRequestId,
|
||||
path: String,
|
||||
},
|
||||
ListDirectory {
|
||||
request_id: crate::project_files::ListingRequestId,
|
||||
#[serde(default)]
|
||||
path: String,
|
||||
#[serde(default)]
|
||||
include_ignored: bool,
|
||||
},
|
||||
ReadProjectFile {
|
||||
request_id: crate::project_files::FileReadRequestId,
|
||||
path: String,
|
||||
},
|
||||
SetFocus {
|
||||
focused: bool,
|
||||
},
|
||||
LinkPullRequest {
|
||||
number: u64,
|
||||
url: String,
|
||||
},
|
||||
PostGithubComment(crate::engine::GithubPost),
|
||||
ChangePullRequest {
|
||||
#[serde(default)]
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
write: crate::engine::PullRequestWrite,
|
||||
},
|
||||
Restack {
|
||||
request_id: crate::restack::RestackId,
|
||||
},
|
||||
Close,
|
||||
}
|
||||
373
crates/luxe-core/src/event/decode/known_event.rs
Normal file
373
crates/luxe-core/src/event/decode/known_event.rs
Normal file
@@ -0,0 +1,373 @@
|
||||
//! The mirror of `Event`'s known variants that serde derives a decoder from.
|
||||
|
||||
use super::super::{
|
||||
EngineState, Event, GuidedReviewFailure, RequestedReviewVerdict, SessionMessage, StopReason,
|
||||
};
|
||||
use crate::activity::ToolActivity;
|
||||
use crate::guided_review::{
|
||||
GuideProvenance, GuidedReview, RemediationReport, ReviewChapter, ReviewId, ReviewLoadRequestId,
|
||||
ReviewRevisionId, ReviewSession, ReviewSessionSaveRequestId, ReviewTarget, SubmissionId,
|
||||
};
|
||||
use crate::message::Message;
|
||||
use crate::permission::PermissionRequestId;
|
||||
use crate::session::EntryId;
|
||||
use crate::workspace::WorkspaceSnapshot;
|
||||
use serde::Deserialize;
|
||||
|
||||
/// [`Event`]'s known variants, field for field; see [`KnownAction`] for how the mirror is held.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(remote = "Event", tag = "kind", content = "content", rename_all = "snake_case")]
|
||||
pub(super) enum KnownEvent {
|
||||
TokenDelta {
|
||||
#[serde(default)]
|
||||
block: usize,
|
||||
delta: String,
|
||||
},
|
||||
ThinkingDelta {
|
||||
#[serde(default)]
|
||||
block: usize,
|
||||
delta: String,
|
||||
},
|
||||
ToolCallComposing {
|
||||
call_id: String,
|
||||
name: String,
|
||||
subject: Option<String>,
|
||||
body: Option<crate::activity::ToolCardBody>,
|
||||
},
|
||||
ToolStarted {
|
||||
call_id: String,
|
||||
name: String,
|
||||
},
|
||||
ToolProgress {
|
||||
call_id: String,
|
||||
chunk: String,
|
||||
},
|
||||
ToolCompleted {
|
||||
call_id: String,
|
||||
is_error: bool,
|
||||
output: String,
|
||||
},
|
||||
ToolEnded {
|
||||
call_id: String,
|
||||
is_error: bool,
|
||||
},
|
||||
MessageCommitted {
|
||||
session_id: String,
|
||||
entry_id: EntryId,
|
||||
message: Message,
|
||||
},
|
||||
RemediationReported {
|
||||
entry_id: EntryId,
|
||||
report: RemediationReport,
|
||||
},
|
||||
ReviewFeedbackTurnDispatched {
|
||||
submission_id: SubmissionId,
|
||||
},
|
||||
ReviewFeedbackTurnFailed {
|
||||
submission_id: SubmissionId,
|
||||
message: String,
|
||||
},
|
||||
ReviewQuestionsAnswered {
|
||||
submission_id: SubmissionId,
|
||||
answer: String,
|
||||
},
|
||||
ReviewFeedbackTurnCompleted {
|
||||
submission_id: SubmissionId,
|
||||
},
|
||||
SessionLoaded {
|
||||
session_id: String,
|
||||
messages: Vec<SessionMessage>,
|
||||
},
|
||||
StateChanged(EngineState),
|
||||
TurnEnded {
|
||||
reason: StopReason,
|
||||
},
|
||||
LastTurnAvailable {
|
||||
session_id: String,
|
||||
turn_id: String,
|
||||
},
|
||||
CompactionDone {
|
||||
tokens_before: u64,
|
||||
tokens_after: u64,
|
||||
},
|
||||
ContextUsage {
|
||||
used_tokens: u32,
|
||||
context_window: u32,
|
||||
},
|
||||
TurnUsage {
|
||||
prompt_tokens: u64,
|
||||
completion_tokens: u64,
|
||||
cost_usd: Option<f64>,
|
||||
#[serde(default)]
|
||||
cache_read_tokens: u64,
|
||||
#[serde(default)]
|
||||
cache_write_tokens: u64,
|
||||
#[serde(default)]
|
||||
reasoning_tokens: u64,
|
||||
#[serde(default)]
|
||||
source: crate::usage::UsageSource,
|
||||
},
|
||||
SessionUsage(crate::usage::SessionUsage),
|
||||
PlanUsage(crate::provider::PlanUsage),
|
||||
ContextComposition(Box<crate::context_report::ContextComposition>),
|
||||
ImageAttached {
|
||||
mime: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
},
|
||||
Error(String),
|
||||
Notice(String),
|
||||
PlanWritten {
|
||||
path: String,
|
||||
},
|
||||
ReviewStarted {
|
||||
model: String,
|
||||
},
|
||||
ReviewFinished {
|
||||
verdict: RequestedReviewVerdict,
|
||||
#[serde(default)]
|
||||
findings: Vec<String>,
|
||||
},
|
||||
SteeringDelivered {
|
||||
count: usize,
|
||||
},
|
||||
ProviderRetrying {
|
||||
attempt: u32,
|
||||
attempts: u32,
|
||||
reason: String,
|
||||
},
|
||||
GuidedReviewLoading {
|
||||
request_id: ReviewLoadRequestId,
|
||||
target: ReviewTarget,
|
||||
},
|
||||
GuidedReviewLoaded {
|
||||
request_id: ReviewLoadRequestId,
|
||||
review: Box<GuidedReview>,
|
||||
},
|
||||
GuidedReviewGuideUpdated {
|
||||
request_id: ReviewLoadRequestId,
|
||||
review_id: ReviewId,
|
||||
revision_id: ReviewRevisionId,
|
||||
chapters: Vec<ReviewChapter>,
|
||||
provenance: GuideProvenance,
|
||||
#[serde(default)]
|
||||
brief: Option<crate::guided_review::ReviewBrief>,
|
||||
},
|
||||
PullRequestPostPrepared {
|
||||
request_id: crate::guided_review::PullRequestPostId,
|
||||
patches: Vec<crate::github::FilePatch>,
|
||||
head_moved: bool,
|
||||
own_pull_request: bool,
|
||||
},
|
||||
PullRequestReviewPosted {
|
||||
request_id: crate::guided_review::PullRequestPostId,
|
||||
github_review_id: u64,
|
||||
url: String,
|
||||
finding_ids: Vec<crate::guided_review::FindingId>,
|
||||
},
|
||||
PullRequestPostFailed {
|
||||
request_id: crate::guided_review::PullRequestPostId,
|
||||
message: String,
|
||||
},
|
||||
ThreadAnswersPrepared {
|
||||
request_id: crate::guided_review::ThreadAnswersId,
|
||||
pushed: bool,
|
||||
uncommitted: bool,
|
||||
},
|
||||
ThreadsAnswered {
|
||||
request_id: crate::guided_review::ThreadAnswersId,
|
||||
results: Vec<crate::guided_review::ThreadAnswerResult>,
|
||||
},
|
||||
ThreadAnswersFailed {
|
||||
request_id: crate::guided_review::ThreadAnswersId,
|
||||
message: String,
|
||||
},
|
||||
GithubListed {
|
||||
repository: Option<String>,
|
||||
sections: Vec<crate::github::ListedSection>,
|
||||
},
|
||||
GithubSearched {
|
||||
request: u64,
|
||||
repository: Option<String>,
|
||||
section: crate::github::ListedSection,
|
||||
},
|
||||
GithubOverviewRead {
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
overview: Option<crate::github::overview::Overview>,
|
||||
error: Option<String>,
|
||||
#[serde(default)]
|
||||
local: Option<crate::github::overview::LocalSession>,
|
||||
},
|
||||
GithubReplyDrafted {
|
||||
request_id: String,
|
||||
body: Option<String>,
|
||||
#[serde(default)]
|
||||
sources: Vec<String>,
|
||||
error: Option<String>,
|
||||
#[serde(default)]
|
||||
note: Option<String>,
|
||||
},
|
||||
PullRequestChanged {
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
change: Option<crate::engine::PullRequestChange>,
|
||||
error: Option<String>,
|
||||
},
|
||||
GithubCommentPosted {
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
thread: Option<String>,
|
||||
url: Option<String>,
|
||||
error: Option<String>,
|
||||
},
|
||||
GithubConversationRead {
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
entries: Option<Vec<crate::github::overview::ConversationEntry>>,
|
||||
error: Option<String>,
|
||||
},
|
||||
StackPrepared {
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
layers: Option<Vec<crate::github::NewPullRequest>>,
|
||||
refusal: Option<String>,
|
||||
},
|
||||
StackOpened {
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
numbers: Vec<u64>,
|
||||
urls: Vec<String>,
|
||||
failed: Option<String>,
|
||||
},
|
||||
RestackPlanned {
|
||||
request_id: crate::restack::RestackId,
|
||||
plan: Option<crate::restack::RestackPlan>,
|
||||
merged: Option<crate::restack::MergedBelow>,
|
||||
refusal: Option<String>,
|
||||
},
|
||||
Restacked {
|
||||
request_id: crate::restack::RestackId,
|
||||
moved: Vec<u64>,
|
||||
retargeted: Vec<u64>,
|
||||
retarget_failed: Option<String>,
|
||||
},
|
||||
RestackFailed {
|
||||
request_id: crate::restack::RestackId,
|
||||
message: String,
|
||||
},
|
||||
PullRequestFixChecked {
|
||||
number: u64,
|
||||
branch: Option<String>,
|
||||
refusal: Option<String>,
|
||||
},
|
||||
PullRequestPrepared {
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
pull_request: crate::github::NewPullRequest,
|
||||
publication: crate::github::Publication,
|
||||
uncommitted: usize,
|
||||
commits: Vec<String>,
|
||||
},
|
||||
PullRequestOpened {
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
number: u64,
|
||||
url: String,
|
||||
committed: Vec<String>,
|
||||
},
|
||||
PullRequestOpenFailed {
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
message: String,
|
||||
},
|
||||
WorktreeRemovalChecked {
|
||||
uncommitted: Vec<String>,
|
||||
},
|
||||
ReviewCommitted {
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
commits: Vec<String>,
|
||||
skipped: Vec<String>,
|
||||
},
|
||||
ReviewCommitFailed {
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
message: String,
|
||||
},
|
||||
GuidedReviewFailed {
|
||||
request_id: ReviewLoadRequestId,
|
||||
target: ReviewTarget,
|
||||
error: GuidedReviewFailure,
|
||||
},
|
||||
FileDiffLoaded {
|
||||
request_id: crate::file_diff::FileDiffRequestId,
|
||||
diff: Box<crate::file_diff::FileDiff>,
|
||||
},
|
||||
FileDiffFailed {
|
||||
request_id: crate::file_diff::FileDiffRequestId,
|
||||
path: String,
|
||||
error: crate::file_diff::FileDiffFailure,
|
||||
},
|
||||
DirectoryListed {
|
||||
request_id: crate::project_files::ListingRequestId,
|
||||
listing: crate::project_files::DirectoryListing,
|
||||
},
|
||||
DirectoryListFailed {
|
||||
request_id: crate::project_files::ListingRequestId,
|
||||
path: String,
|
||||
error: crate::project_files::ProjectFileFailure,
|
||||
},
|
||||
ProjectFileRead {
|
||||
request_id: crate::project_files::FileReadRequestId,
|
||||
file: Box<crate::project_files::ProjectFile>,
|
||||
},
|
||||
ProjectFileReadFailed {
|
||||
request_id: crate::project_files::FileReadRequestId,
|
||||
path: String,
|
||||
error: crate::project_files::ProjectFileFailure,
|
||||
},
|
||||
ReviewSessionRestored {
|
||||
session: Box<ReviewSession>,
|
||||
},
|
||||
ReviewSessionSaved {
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
session: Box<ReviewSession>,
|
||||
},
|
||||
ReviewSessionSaveFailed {
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
review_id: ReviewId,
|
||||
message: String,
|
||||
},
|
||||
SessionsRefreshed(Vec<String>),
|
||||
WorkspaceRefreshRequested,
|
||||
TerminalFocusChanged {
|
||||
focused: bool,
|
||||
},
|
||||
WorkspaceUpdated(Box<WorkspaceSnapshot>),
|
||||
ToolActivityUpdated(Box<ToolActivity>),
|
||||
PermissionRequested {
|
||||
id: PermissionRequestId,
|
||||
session_id: String,
|
||||
tool: String,
|
||||
permission: String,
|
||||
summary: String,
|
||||
#[serde(default)]
|
||||
always_patterns: Vec<String>,
|
||||
},
|
||||
QuestionAsked {
|
||||
id: crate::question::QuestionRequestId,
|
||||
session_id: String,
|
||||
prompt: String,
|
||||
#[serde(default)]
|
||||
options: Vec<crate::question::QuestionOption>,
|
||||
#[serde(default)]
|
||||
multi: bool,
|
||||
},
|
||||
Ready {
|
||||
protocol_version: u32,
|
||||
luxe_version: String,
|
||||
session_id: String,
|
||||
cwd: String,
|
||||
#[serde(default)]
|
||||
github_writes: bool,
|
||||
},
|
||||
ActionRejected {
|
||||
#[serde(default)]
|
||||
kind: Option<String>,
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
622
crates/luxe-core/src/event/events.rs
Normal file
622
crates/luxe-core/src/event/events.rs
Normal file
@@ -0,0 +1,622 @@
|
||||
//! Event — the core→UI half of the protocol.
|
||||
|
||||
use super::{EngineState, GuidedReviewFailure, RequestedReviewVerdict, SessionMessage, StopReason};
|
||||
use crate::activity::ToolActivity;
|
||||
use crate::guided_review::{
|
||||
GuideProvenance, GuidedReview, RemediationReport, ReviewChapter, ReviewId, ReviewLoadRequestId,
|
||||
ReviewRevisionId, ReviewSession, ReviewSessionSaveRequestId, ReviewTarget, SubmissionId,
|
||||
};
|
||||
use crate::message::Message;
|
||||
use crate::permission::PermissionRequestId;
|
||||
use crate::session::EntryId;
|
||||
use crate::workspace::WorkspaceSnapshot;
|
||||
use serde::Serialize;
|
||||
|
||||
/// core→UI stream. `#[non_exhaustive]` so later phases can add variants.
|
||||
/// Unknown variants deserialize into [`Event::Other`] and are preserved verbatim.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(tag = "kind", content = "content", rename_all = "snake_case")]
|
||||
#[non_exhaustive]
|
||||
pub enum Event {
|
||||
/// A token fragment of the next assistant text block (block index is for ordering).
|
||||
TokenDelta { block: usize, delta: String },
|
||||
/// A reasoning/thinking token fragment.
|
||||
ThinkingDelta { block: usize, delta: String },
|
||||
/// The model has begun writing a tool call, well before it can be dispatched.
|
||||
///
|
||||
/// A `write`'s content *is* its argument, so the model spends far longer composing that call
|
||||
/// than the tool spends running it. Without this the transcript has nothing to show for that
|
||||
/// stretch, and the card lands at the same moment the work finishes — which reads as a tool
|
||||
/// that never ran. [`Event::ToolStarted`] follows with the same `call_id` once it is
|
||||
/// dispatched, and every call that composes also ends, so a front-end may open a row here and
|
||||
/// settle it there.
|
||||
///
|
||||
/// `subject` is best effort: absent on the first frame, then sent once more as soon as the
|
||||
/// arguments that have landed name what the call is about (`describe_partial_call`). A call
|
||||
/// whose bulky argument arrives first is never named and simply stays a spinner.
|
||||
///
|
||||
/// `body` is the payload as far as it has been written, for the tools whose payload is the
|
||||
/// point (`partial_card_body`), and is resent as it grows — rate-limited, not per fragment.
|
||||
/// Its `total_lines` counts what has landed, so a card's `+N more lines` climbs while the file
|
||||
/// is written. Every field is a snapshot rather than a delta, so a client may drop any frame.
|
||||
ToolCallComposing {
|
||||
call_id: String,
|
||||
name: String,
|
||||
subject: Option<String>,
|
||||
body: Option<crate::activity::ToolCardBody>,
|
||||
},
|
||||
/// Tool invocation started (name + id known before execution).
|
||||
ToolStarted { call_id: String, name: String },
|
||||
/// Streaming progress from a running tool.
|
||||
ToolProgress { call_id: String, chunk: String },
|
||||
/// A call finished running, with what it returned, before its message's results commit.
|
||||
///
|
||||
/// A call can run while the model is still writing the next one, so its result exists well
|
||||
/// before the batch's results are committed and `ToolEnded` follows. This is what lets a card
|
||||
/// settle the moment its own call does instead of when the last of the batch does. Optional for
|
||||
/// a client: one that ignores it settles the card on `ToolEnded`, as before. `output` is the
|
||||
/// result's text, already redacted. Args: `{call_id, is_error, output}`.
|
||||
ToolCompleted { call_id: String, is_error: bool, output: String },
|
||||
/// Tool finished (success or error).
|
||||
ToolEnded { call_id: String, is_error: bool },
|
||||
/// A full assistant message was committed to the session.
|
||||
MessageCommitted {
|
||||
/// Session which owns the persisted entry.
|
||||
session_id: String,
|
||||
/// Persisted entry which owns this message.
|
||||
entry_id: EntryId,
|
||||
/// Committed message content.
|
||||
message: Message,
|
||||
},
|
||||
/// A validated remediation report was extracted after its assistant transcript entry committed.
|
||||
RemediationReported {
|
||||
/// Persisted assistant entry that carried the named report block.
|
||||
entry_id: EntryId,
|
||||
/// Source-pinned result data safe to apply to matching review feedback.
|
||||
report: RemediationReport,
|
||||
},
|
||||
/// A queued feedback item crossed the engine boundary and can no longer be cancelled.
|
||||
ReviewFeedbackTurnDispatched {
|
||||
/// Immutable feedback submission whose agent turn is about to begin.
|
||||
submission_id: SubmissionId,
|
||||
},
|
||||
/// A feedback turn failed before the engine could produce a terminal agent response.
|
||||
ReviewFeedbackTurnFailed {
|
||||
/// Persisted feedback submission whose turn failed.
|
||||
submission_id: SubmissionId,
|
||||
/// Display-safe, bounded failure detail.
|
||||
message: String,
|
||||
},
|
||||
/// A question's turn answered, just before it completes: the answer belongs on the
|
||||
/// questions it was asked about, not only in the transcript.
|
||||
ReviewQuestionsAnswered {
|
||||
/// Persisted feedback submission that asked
|
||||
submission_id: SubmissionId,
|
||||
/// The turn's final reply
|
||||
answer: String,
|
||||
},
|
||||
/// A feedback turn reached its terminal assistant response and may be marked complete.
|
||||
ReviewFeedbackTurnCompleted {
|
||||
/// Persisted feedback submission whose turn completed.
|
||||
submission_id: SubmissionId,
|
||||
},
|
||||
/// A resumed session was loaded with its active-path transcript.
|
||||
SessionLoaded {
|
||||
/// Active session identity.
|
||||
session_id: String,
|
||||
/// Active-path messages paired with their persisted entry IDs.
|
||||
messages: Vec<SessionMessage>,
|
||||
},
|
||||
/// Engine state snapshot changed.
|
||||
StateChanged(EngineState),
|
||||
/// The in-flight turn ended.
|
||||
TurnEnded { reason: StopReason },
|
||||
/// A complete retained baseline is available for the latest agent turn.
|
||||
LastTurnAvailable {
|
||||
/// Session which owns the persisted baseline.
|
||||
session_id: String,
|
||||
/// Opaque turn key accepted by `ReviewTarget::LastTurn`.
|
||||
turn_id: String,
|
||||
},
|
||||
/// Compaction completed.
|
||||
CompactionDone { tokens_before: u64, tokens_after: u64 },
|
||||
/// Token usage after a provider call — lets UIs show context-window fullness.
|
||||
ContextUsage { used_tokens: u32, context_window: u32 },
|
||||
/// Token counts + cost for **one provider call**, as it completes.
|
||||
///
|
||||
/// Per call, not per turn: a turn that calls tools makes many, and each reports its own usage.
|
||||
/// Anything that wants a running total should read [`Event::SessionUsage`] rather than trying
|
||||
/// to reduce this stream — the engine already did the arithmetic.
|
||||
TurnUsage {
|
||||
prompt_tokens: u64,
|
||||
completion_tokens: u64,
|
||||
cost_usd: Option<f64>,
|
||||
/// Cached input tokens read (subset of `prompt_tokens`).
|
||||
#[serde(default)]
|
||||
cache_read_tokens: u64,
|
||||
/// Input tokens written to cache (subset of `prompt_tokens`).
|
||||
#[serde(default)]
|
||||
cache_write_tokens: u64,
|
||||
/// Reasoning tokens (subset of `completion_tokens`).
|
||||
#[serde(default)]
|
||||
reasoning_tokens: u64,
|
||||
/// Which part of the harness made the call.
|
||||
#[serde(default)]
|
||||
source: crate::usage::UsageSource,
|
||||
},
|
||||
/// The session's running spend after the call [`Event::TurnUsage`] just reported.
|
||||
///
|
||||
/// The authoritative figure: totals plus the per-source breakdown behind them. UIs render it
|
||||
/// and perform no accounting of their own.
|
||||
SessionUsage(crate::usage::SessionUsage),
|
||||
/// How much of a subscription's allowance is left, as the provider reported it on the last
|
||||
/// call. Absent for API-key providers, which meter money rather than a plan.
|
||||
PlanUsage(crate::provider::PlanUsage),
|
||||
/// What the next request would carry, broken into parts — the answer to `/context`.
|
||||
///
|
||||
/// Boxed: it dwarfs every other variant, and this enum is moved through a channel on every
|
||||
/// streamed token.
|
||||
ContextComposition(Box<crate::context_report::ContextComposition>),
|
||||
/// An image was attached to the current message (clipboard paste or file drop).
|
||||
ImageAttached { mime: String, width: u32, height: u32 },
|
||||
/// A non-recoverable error occurred.
|
||||
Error(String),
|
||||
/// An informational message for the user. Unlike [`Event::Error`] it does not end the turn.
|
||||
Notice(String),
|
||||
/// Plan mode wrote one of its plan files. Args: `path`, project-relative.
|
||||
///
|
||||
/// What a front-end offers the plan's next step on, once the turn that wrote it ends.
|
||||
PlanWritten { path: String },
|
||||
/// A requested review started, on `model`, so a front-end can say one is running.
|
||||
ReviewStarted { model: String },
|
||||
/// A requested review came back. Args: `verdict`, and `findings` — each one a reviewer would
|
||||
/// fix, or the reason none came back.
|
||||
ReviewFinished { verdict: RequestedReviewVerdict, findings: Vec<String> },
|
||||
/// Steering messages buffered during the turn were delivered to the model at a checkpoint.
|
||||
/// Args: `count` — how many, in admission order, so a UI can clear their pending markers.
|
||||
SteeringDelivered { count: usize },
|
||||
/// The provider could not answer just now, before saying anything, and the same request goes
|
||||
/// out again after a pause. Args: `attempt` of `attempts`, and `reason`, the provider's words.
|
||||
ProviderRetrying { attempt: u32, attempts: u32, reason: String },
|
||||
/// A requested immutable Guided Review source started loading.
|
||||
GuidedReviewLoading {
|
||||
/// Correlates this state with the request that caused it.
|
||||
request_id: ReviewLoadRequestId,
|
||||
/// Target currently being captured.
|
||||
target: ReviewTarget,
|
||||
},
|
||||
/// A requested immutable Guided Review source was captured and assembled.
|
||||
GuidedReviewLoaded {
|
||||
/// Correlates this review with the request that produced it.
|
||||
request_id: ReviewLoadRequestId,
|
||||
/// Complete review derived only from its pinned source artifact.
|
||||
review: Box<GuidedReview>,
|
||||
},
|
||||
/// A richer Guide replaced the structural chapters a review opened with.
|
||||
///
|
||||
/// Chaptering is advisory and can involve several model passes, so it must never hold the diff
|
||||
/// hostage: the review opens immediately with deterministic sections and upgrades in place when
|
||||
/// (and only when) the pinned revision it describes is still the one on screen.
|
||||
GuidedReviewGuideUpdated {
|
||||
/// Correlates this Guide with the request whose review it describes.
|
||||
request_id: ReviewLoadRequestId,
|
||||
/// Logical review the chapters belong to.
|
||||
review_id: ReviewId,
|
||||
/// Exact pinned revision the chapters were computed against.
|
||||
revision_id: ReviewRevisionId,
|
||||
/// Replacement chapters, already validated to cover every source item once.
|
||||
chapters: Vec<ReviewChapter>,
|
||||
/// How those chapters were produced.
|
||||
provenance: GuideProvenance,
|
||||
/// The reviewer-facing summary from the same pass, when it produced one.
|
||||
#[serde(default)]
|
||||
brief: Option<crate::guided_review::ReviewBrief>,
|
||||
},
|
||||
/// What a pull request's review needs before it is posted.
|
||||
PullRequestPostPrepared {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::PullRequestPostId,
|
||||
/// GitHub's patches, which decide where each comment can land
|
||||
patches: Vec<crate::github::FilePatch>,
|
||||
/// Whether the author pushed after the review was pinned
|
||||
head_moved: bool,
|
||||
/// Whether the reader opened the pull request, which rules out approving it
|
||||
own_pull_request: bool,
|
||||
},
|
||||
/// A pull request's review landed on GitHub.
|
||||
PullRequestReviewPosted {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::PullRequestPostId,
|
||||
/// GitHub's id for the review
|
||||
github_review_id: u64,
|
||||
/// Where it can be read
|
||||
url: String,
|
||||
/// The comments it carried
|
||||
finding_ids: Vec<crate::guided_review::FindingId>,
|
||||
},
|
||||
/// Preparing or posting a pull request's review failed; nothing was posted.
|
||||
PullRequestPostFailed {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::PullRequestPostId,
|
||||
/// What went wrong, as a sentence
|
||||
message: String,
|
||||
},
|
||||
/// Whether the fixes behind a thread answer are on GitHub yet.
|
||||
ThreadAnswersPrepared {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::ThreadAnswersId,
|
||||
/// Whether the checkout's `HEAD` is the pull request's head on GitHub
|
||||
pushed: bool,
|
||||
/// Whether the working tree has changes not committed
|
||||
uncommitted: bool,
|
||||
},
|
||||
/// What answering each thread did.
|
||||
ThreadsAnswered {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::ThreadAnswersId,
|
||||
/// One per thread asked about, in order
|
||||
results: Vec<crate::guided_review::ThreadAnswerResult>,
|
||||
},
|
||||
/// Preparing or sending thread answers failed before any thread was touched.
|
||||
ThreadAnswersFailed {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::ThreadAnswersId,
|
||||
/// What went wrong, as a sentence
|
||||
message: String,
|
||||
},
|
||||
/// What `/github`'s sections found.
|
||||
GithubListed {
|
||||
/// The checkout's repository, `owner/name`, which a row elsewhere is told apart from
|
||||
repository: Option<String>,
|
||||
/// Each section, in the order asked, with its rows or its reason
|
||||
sections: Vec<crate::github::ListedSection>,
|
||||
},
|
||||
/// One search `/github` ran on its own: a tab's edited query, or the next page of one.
|
||||
GithubSearched {
|
||||
/// The front-end's id for the search, as asked
|
||||
request: u64,
|
||||
/// The checkout's repository, `owner/name`, which a row elsewhere is told apart from
|
||||
repository: Option<String>,
|
||||
/// What it found, or why nothing
|
||||
section: crate::github::ListedSection,
|
||||
},
|
||||
/// One pull request's or issue's overview, or why it could not be read.
|
||||
GithubOverviewRead {
|
||||
/// `owner/name` as asked, `None` for the checkout's repository
|
||||
repository: Option<String>,
|
||||
/// The number asked about
|
||||
number: u64,
|
||||
/// What GitHub said about it
|
||||
overview: Option<crate::github::overview::Overview>,
|
||||
/// Why it could not be read, as a sentence
|
||||
error: Option<String>,
|
||||
/// Your latest other session on it, for an issue on the checkout's repository that has one
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
local: Option<crate::github::overview::LocalSession>,
|
||||
},
|
||||
/// A reply the agent drafted for the reader to read, change and send, or why there is none.
|
||||
GithubReplyDrafted {
|
||||
/// The request it answers
|
||||
request_id: String,
|
||||
/// The draft, markdown
|
||||
body: Option<String>,
|
||||
/// What it was drafted from, as a person says it: `this session`, `the thread`
|
||||
sources: Vec<String>,
|
||||
/// Why there is no draft, as a sentence
|
||||
error: Option<String>,
|
||||
/// What the agent said beside the draft — a caveat to read before sending it
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
note: Option<String>,
|
||||
},
|
||||
/// A change the reader made to a pull request landed, or why it did not.
|
||||
PullRequestChanged {
|
||||
/// `owner/name` as asked, `None` for the checkout's repository
|
||||
repository: Option<String>,
|
||||
/// The pull request changed
|
||||
number: u64,
|
||||
/// What changed
|
||||
change: Option<crate::engine::PullRequestChange>,
|
||||
/// Why nothing did, as a sentence
|
||||
error: Option<String>,
|
||||
},
|
||||
/// A reply or comment the reader posted landed, or why it did not.
|
||||
GithubCommentPosted {
|
||||
/// `owner/name` as asked, `None` for the checkout's repository
|
||||
repository: Option<String>,
|
||||
/// The pull request or issue it was on
|
||||
number: u64,
|
||||
/// The thread it replied in, when it answered one
|
||||
thread: Option<String>,
|
||||
/// Where it can be read, once it landed
|
||||
url: Option<String>,
|
||||
/// Why it did not land, as a sentence
|
||||
error: Option<String>,
|
||||
},
|
||||
/// Everything said about a pull request or an issue, or why it could not be read.
|
||||
GithubConversationRead {
|
||||
/// `owner/name` as asked, `None` for the checkout's repository
|
||||
repository: Option<String>,
|
||||
/// The number asked about
|
||||
number: u64,
|
||||
/// Its conversation, oldest first
|
||||
entries: Option<Vec<crate::github::overview::ConversationEntry>>,
|
||||
/// Why it could not be read, as a sentence
|
||||
error: Option<String>,
|
||||
},
|
||||
/// A branch's review drafted as a stack.
|
||||
StackPrepared {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
/// The pull requests, bottom first, each on the branch of the one below
|
||||
layers: Option<Vec<crate::github::NewPullRequest>>,
|
||||
/// Why it cannot be a stack, as a sentence
|
||||
refusal: Option<String>,
|
||||
},
|
||||
/// A stack opened from a review, all of it or as far as it got.
|
||||
StackOpened {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
/// The pull requests that opened, bottom first
|
||||
numbers: Vec<u64>,
|
||||
/// Where each can be read, in the same order
|
||||
urls: Vec<String>,
|
||||
/// What stopped the rest, as a sentence
|
||||
failed: Option<String>,
|
||||
},
|
||||
/// What restacking the checked-out branch's stack would do.
|
||||
RestackPlanned {
|
||||
/// Names the plan, for the `restack` that confirms it
|
||||
request_id: crate::restack::RestackId,
|
||||
/// The plan; its steps are empty when the stack already sits right
|
||||
plan: Option<crate::restack::RestackPlan>,
|
||||
/// The pull request that merged out from under the stack's bottom, when one did
|
||||
merged: Option<crate::restack::MergedBelow>,
|
||||
/// Why there is no plan, as a sentence
|
||||
refusal: Option<String>,
|
||||
},
|
||||
/// A restack was pushed.
|
||||
Restacked {
|
||||
/// The plan that was pushed
|
||||
request_id: crate::restack::RestackId,
|
||||
/// Pull requests whose branch moved
|
||||
moved: Vec<u64>,
|
||||
/// Pull requests moved to a new base
|
||||
retargeted: Vec<u64>,
|
||||
/// A base that could not be moved, after the push, as a sentence
|
||||
retarget_failed: Option<String>,
|
||||
},
|
||||
/// A restack failed before anything was pushed.
|
||||
RestackFailed {
|
||||
/// The plan the push named
|
||||
request_id: crate::restack::RestackId,
|
||||
/// What went wrong, as a sentence
|
||||
message: String,
|
||||
},
|
||||
/// Whether a pull request can be checked out here to fix.
|
||||
PullRequestFixChecked {
|
||||
/// Number within its repository
|
||||
number: u64,
|
||||
/// The local branch it would be checked out on, when it can be
|
||||
branch: Option<String>,
|
||||
/// Why it cannot, as a sentence
|
||||
refusal: Option<String>,
|
||||
},
|
||||
/// The pull request a branch's review would open, drafted for the reader to edit.
|
||||
PullRequestPrepared {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
/// The draft: head, base, title and description
|
||||
pull_request: crate::github::NewPullRequest,
|
||||
/// Whether the branch is on GitHub yet; opening pushes it when it is not
|
||||
publication: crate::github::Publication,
|
||||
/// Paths with changes not committed
|
||||
uncommitted: usize,
|
||||
/// Subjects of the commits opening writes first, when the reviewed work is not committed
|
||||
commits: Vec<String>,
|
||||
},
|
||||
/// A branch's pull request opened on GitHub.
|
||||
PullRequestOpened {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
/// Its number
|
||||
number: u64,
|
||||
/// Where it can be read
|
||||
url: String,
|
||||
/// Commits written before it opened
|
||||
committed: Vec<String>,
|
||||
},
|
||||
/// Drafting or opening a pull request failed; nothing was opened.
|
||||
PullRequestOpenFailed {
|
||||
/// The attempt this answers
|
||||
request_id: crate::guided_review::PullRequestOpenId,
|
||||
/// What went wrong, as a sentence
|
||||
message: String,
|
||||
},
|
||||
/// What in the session's worktree is not committed, asked just before removing it.
|
||||
WorktreeRemovalChecked {
|
||||
/// Paths with changes not committed, as git names them; empty when removing loses nothing
|
||||
uncommitted: Vec<String>,
|
||||
},
|
||||
/// The reviewed change reached the log.
|
||||
ReviewCommitted {
|
||||
/// Correlates this outcome with the request that asked for it.
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
/// New commit object IDs, oldest first.
|
||||
commits: Vec<String>,
|
||||
/// Reviewed items no patch could carry, named so nothing vanishes silently.
|
||||
skipped: Vec<String>,
|
||||
},
|
||||
/// The reviewed change could not be committed, and nothing was changed.
|
||||
ReviewCommitFailed {
|
||||
/// Correlates this failure with the request that asked for it.
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
/// Reviewer-facing explanation.
|
||||
message: String,
|
||||
},
|
||||
/// A requested immutable Guided Review source could not be loaded.
|
||||
GuidedReviewFailed {
|
||||
/// Correlates this failure with the request that produced it.
|
||||
request_id: ReviewLoadRequestId,
|
||||
/// Target whose immutable source was unavailable.
|
||||
target: ReviewTarget,
|
||||
/// Typed, bounded failure safe to render or serialize.
|
||||
error: GuidedReviewFailure,
|
||||
},
|
||||
/// One file's change was captured for a glance, outside any review.
|
||||
FileDiffLoaded {
|
||||
/// Correlates this capture with the request that asked for it.
|
||||
request_id: crate::file_diff::FileDiffRequestId,
|
||||
/// The file's change, or an explicit absence when it matches its base.
|
||||
diff: Box<crate::file_diff::FileDiff>,
|
||||
},
|
||||
/// One file's change could not be captured.
|
||||
FileDiffFailed {
|
||||
/// Correlates this failure with the request that asked for it.
|
||||
request_id: crate::file_diff::FileDiffRequestId,
|
||||
/// Path whose change was asked for.
|
||||
path: String,
|
||||
/// Typed, bounded failure safe to render or serialize.
|
||||
error: crate::file_diff::FileDiffFailure,
|
||||
},
|
||||
/// One project folder was listed.
|
||||
DirectoryListed {
|
||||
/// Correlates this listing with the request that asked for it.
|
||||
request_id: crate::project_files::ListingRequestId,
|
||||
/// The folder's entries.
|
||||
listing: crate::project_files::DirectoryListing,
|
||||
},
|
||||
/// One project folder could not be listed.
|
||||
DirectoryListFailed {
|
||||
/// Correlates this failure with the request that asked for it.
|
||||
request_id: crate::project_files::ListingRequestId,
|
||||
/// Folder that was asked for.
|
||||
path: String,
|
||||
/// Why not.
|
||||
error: crate::project_files::ProjectFileFailure,
|
||||
},
|
||||
/// One project file was read for a preview.
|
||||
ProjectFileRead {
|
||||
/// Correlates this read with the request that asked for it.
|
||||
request_id: crate::project_files::FileReadRequestId,
|
||||
/// The file's text, or the fact that it has none.
|
||||
file: Box<crate::project_files::ProjectFile>,
|
||||
},
|
||||
/// One project file could not be read.
|
||||
ProjectFileReadFailed {
|
||||
/// Correlates this failure with the request that asked for it.
|
||||
request_id: crate::project_files::FileReadRequestId,
|
||||
/// File that was asked for.
|
||||
path: String,
|
||||
/// Why not.
|
||||
error: crate::project_files::ProjectFileFailure,
|
||||
},
|
||||
/// The feedback session bound to the review just loaded, which always follows
|
||||
/// [`Event::GuidedReviewLoaded`]: carried over a refresh and moved onto its new source,
|
||||
/// restored from disk after a restart, or new. Also sent when another writer's copy replaced
|
||||
/// this one.
|
||||
ReviewSessionRestored {
|
||||
/// Complete authoritative state, as the review desk holds it.
|
||||
session: Box<ReviewSession>,
|
||||
},
|
||||
/// The open review's feedback session changed and was stored.
|
||||
///
|
||||
/// Every change arrives this way, whoever made it: an `EditReview`, answered under its
|
||||
/// `request_id`, or something Luxe did itself (a turn dispatched, a report recorded, a review
|
||||
/// posted), under a fresh one.
|
||||
ReviewSessionSaved {
|
||||
/// The edit this answers, or a fresh id for a change Luxe made itself.
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
/// Complete authoritative state returned by the expected-revision store.
|
||||
session: Box<ReviewSession>,
|
||||
},
|
||||
/// A change to the feedback session was refused or could not be stored, and nothing changed.
|
||||
ReviewSessionSaveFailed {
|
||||
/// The edit this answers, or a fresh id for a change Luxe made itself.
|
||||
request_id: ReviewSessionSaveRequestId,
|
||||
/// Logical review whose mutable state was not persisted.
|
||||
review_id: ReviewId,
|
||||
/// Concise recovery guidance safe to show in the UI.
|
||||
message: String,
|
||||
},
|
||||
/// Session list was refreshed.
|
||||
SessionsRefreshed(Vec<String>),
|
||||
/// Project-local workspace refresh was explicitly requested.
|
||||
WorkspaceRefreshRequested,
|
||||
/// The terminal gained or lost focus.
|
||||
///
|
||||
/// The workspace runtime paces its background GitHub refreshes on it: a terminal nobody has
|
||||
/// looked at for a while is checked less often, and one coming back is checked at once.
|
||||
TerminalFocusChanged {
|
||||
/// Whether it now has focus
|
||||
focused: bool,
|
||||
},
|
||||
/// Project-local workspace summary changed.
|
||||
WorkspaceUpdated(Box<WorkspaceSnapshot>),
|
||||
/// Structured display state for a tool call changed.
|
||||
///
|
||||
/// Boxed like [`Event::WorkspaceUpdated`]: it is far and away the largest payload here, and every
|
||||
/// event on the channel — a token delta, a spinner tick — pays for the biggest variant.
|
||||
ToolActivityUpdated(Box<ToolActivity>),
|
||||
/// A tool call needs the user's approval (permission `ask`). The front-end shows a prompt and
|
||||
/// replies with `Action::RespondPermission` carrying the same `id`.
|
||||
PermissionRequested {
|
||||
/// Correlates this prompt with its `RespondPermission` reply.
|
||||
id: PermissionRequestId,
|
||||
/// Session that owns the awaiting turn.
|
||||
session_id: String,
|
||||
/// Tool being invoked (e.g. `bash`, `edit`).
|
||||
tool: String,
|
||||
/// Permission key the decision was keyed on (e.g. `bash`, `external_directory`).
|
||||
permission: String,
|
||||
/// One-line, human-readable description of the action (e.g. `Run: rm -rf build`).
|
||||
summary: String,
|
||||
/// Patterns an "always" reply would approve for the session (for display).
|
||||
always_patterns: Vec<String>,
|
||||
},
|
||||
/// The interactive `question` tool needs the user's answer. The front-end shows a modal and
|
||||
/// replies with `Action::AnswerQuestion` carrying the same `id`.
|
||||
QuestionAsked {
|
||||
/// Correlates this prompt with its `AnswerQuestion` reply.
|
||||
id: crate::question::QuestionRequestId,
|
||||
/// Session that owns the awaiting turn.
|
||||
session_id: String,
|
||||
/// The question to put to the user.
|
||||
prompt: String,
|
||||
/// Selectable options with their rationale (may be empty for a free-text-only question).
|
||||
options: Vec<crate::question::QuestionOption>,
|
||||
/// Whether multiple options may be selected.
|
||||
multi: bool,
|
||||
},
|
||||
/// First frame of an RPC stream: which protocol the peer is speaking, and to what.
|
||||
///
|
||||
/// Emitted by `luxe --rpc` before anything else, so a client checks one integer and refuses a
|
||||
/// build it cannot speak to. Additive changes do not move `protocol_version`; removing or
|
||||
/// retagging anything does. `docs/guide/rpc.md`.
|
||||
Ready {
|
||||
/// Wire protocol version — [`crate::PROTOCOL_VERSION`].
|
||||
protocol_version: u32,
|
||||
/// The Luxe build serving this session.
|
||||
luxe_version: String,
|
||||
/// Session the stream is attached to.
|
||||
session_id: String,
|
||||
/// Project root the agent was opened in.
|
||||
cwd: String,
|
||||
/// Whether this session accepts actions that publish to GitHub (`--github-writes`), so a
|
||||
/// client can hide what would only be refused.
|
||||
#[serde(default)]
|
||||
github_writes: bool,
|
||||
},
|
||||
/// An inbound frame was refused and had no effect.
|
||||
///
|
||||
/// Recoverable by construction, unlike [`Event::Error`] — one malformed line costs a client
|
||||
/// that line, not its session.
|
||||
ActionRejected {
|
||||
/// The refused `kind`, or absent when the line never parsed far enough to have one.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
kind: Option<String>,
|
||||
/// What was wrong with it.
|
||||
reason: String,
|
||||
},
|
||||
/// Catch-all for future variants the builder didn't know about.
|
||||
Other { kind: String, content: serde_json::Value },
|
||||
}
|
||||
731
crates/luxe-core/src/event/tests.rs
Normal file
731
crates/luxe-core/src/event/tests.rs
Normal file
@@ -0,0 +1,731 @@
|
||||
use super::*;
|
||||
use crate::activity::ToolActivity;
|
||||
use crate::guided_review::{
|
||||
GuidedReview, RemediationReport, ReviewId, ReviewLoadRequestId, ReviewRevisionId,
|
||||
ReviewSession, ReviewTarget, SubmissionId,
|
||||
};
|
||||
use crate::message::Message;
|
||||
use crate::permission::PermissionRequestId;
|
||||
use crate::session::EntryId;
|
||||
use crate::workspace::WorkspaceSnapshot;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
mod decoding;
|
||||
mod samples;
|
||||
use samples::{tag_of, EVENT_TAGS};
|
||||
|
||||
fn roundtrip<T: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug>(
|
||||
name: &str,
|
||||
value: &T,
|
||||
) {
|
||||
let json = serde_json::to_string(value).expect("serialize");
|
||||
let decoded: T = serde_json::from_str(&json).expect("deserialize");
|
||||
assert_eq!(&decoded, value, "{} round-trip mismatch", name);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_ref_roundtrip() {
|
||||
let m = ModelRef::new("openai", "gpt-4o");
|
||||
roundtrip("model ref", &m);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_ref_with_base_url_roundtrip() {
|
||||
let m = ModelRef::new("anthropic", "claude-sonnet-4-20250514")
|
||||
.with_base_url("http://localhost:8080");
|
||||
roundtrip("model ref (base_url)", &m);
|
||||
}
|
||||
|
||||
/// A request id parsed from its wire form, so a pinned literal stays deterministic.
|
||||
///
|
||||
/// Doubles as an assertion that these ids really are plain strings on the wire: if one grew a
|
||||
/// struct shape, every call here would stop deserializing.
|
||||
fn id<T: for<'de> Deserialize<'de>>(literal: &str) -> T {
|
||||
serde_json::from_value(serde_json::json!(literal)).expect("request ids are wire strings")
|
||||
}
|
||||
|
||||
/// One representative value per wire [`Action`] variant, `Other` excluded.
|
||||
///
|
||||
/// `every_action_variant_is_sampled` holds it complete against [`action_tag_of`], which the
|
||||
/// compiler holds complete against the enum.
|
||||
fn sample_actions() -> Vec<Action> {
|
||||
vec![
|
||||
Action::SubmitUserMessage {
|
||||
text: "summarize the diff".into(),
|
||||
images: vec![crate::engine::ImageAttachment {
|
||||
data: "aGk=".into(),
|
||||
mime: "image/png".into(),
|
||||
name: Some("shot.png".into()),
|
||||
}],
|
||||
},
|
||||
Action::SteerTurn { text: "check the windows path too".into() },
|
||||
Action::WithdrawSteering,
|
||||
Action::Cancel,
|
||||
Action::EditResend { text: "summarize the diff, briefly".into() },
|
||||
Action::Retry,
|
||||
Action::Regenerate,
|
||||
Action::RespondPermission {
|
||||
id: id("perm:1"),
|
||||
reply: crate::permission::PermissionReply::AlwaysPersist,
|
||||
},
|
||||
Action::AnswerQuestion {
|
||||
id: id("ask:1"),
|
||||
reply: crate::question::QuestionReply::Answered(vec!["postgres".into()]),
|
||||
},
|
||||
Action::SetPermissionAutoApprove(true),
|
||||
Action::SelectModel(ModelRef::new("anthropic", "claude-sonnet-4-20250514")),
|
||||
Action::SetThinkingLevel(crate::provider::ThinkingLevel::High),
|
||||
Action::SetMode("plan".into()),
|
||||
Action::RequestReview { focus: Some("error handling".into()) },
|
||||
Action::NewSession,
|
||||
Action::LoadSession("session-1".into()),
|
||||
Action::RefreshSessions,
|
||||
Action::RefreshWorkspace,
|
||||
Action::RequestContextComposition,
|
||||
Action::CompactNow { focus: Some("the API decisions".into()) },
|
||||
Action::LoadGuidedReview {
|
||||
request_id: id("review-load:1"),
|
||||
target: ReviewTarget::WorkingTree,
|
||||
},
|
||||
Action::EditReview {
|
||||
request_id: id("review-save:1"),
|
||||
review_id: id("review:1"),
|
||||
edit: crate::engine::ReviewEdit::Comment {
|
||||
draft: crate::engine::CommentDraft {
|
||||
anchor: crate::guided_review::FindingAnchor::Line {
|
||||
file_id: id("file:1"),
|
||||
hunk_id: id("hunk:1"),
|
||||
side: crate::guided_review::DiffSide::New,
|
||||
line: 12,
|
||||
context_hash: String::new(),
|
||||
},
|
||||
severity: crate::guided_review::FindingSeverity::Question,
|
||||
title: String::new(),
|
||||
body: "Why does this retry twice?".into(),
|
||||
proposed_fix: None,
|
||||
},
|
||||
send: true,
|
||||
},
|
||||
},
|
||||
Action::RecordReviewProgress {
|
||||
review_id: id("review:1"),
|
||||
walked_chapter_ids: vec![id("chapter:1")],
|
||||
},
|
||||
Action::RecordReviewSeen { review_id: id("review:1") },
|
||||
Action::RefreshGuidedReview {
|
||||
request_id: id("review-load:2"),
|
||||
review_id: id("review:1"),
|
||||
revision_id: id("revision:1"),
|
||||
},
|
||||
Action::CommitReviewChapters {
|
||||
request_id: id("review-save:2"),
|
||||
review_id: id("review:1"),
|
||||
revision_id: id("revision:1"),
|
||||
chapter_ids: Vec::new(),
|
||||
squash: true,
|
||||
},
|
||||
Action::PreparePullRequest { request_id: id("pr-open:1"), review_id: id("review:1") },
|
||||
Action::OpenPullRequest {
|
||||
request_id: id("pr-open:1"),
|
||||
title: "Retry once".into(),
|
||||
body: "Why.".into(),
|
||||
draft: false,
|
||||
},
|
||||
Action::PrepareStack { request_id: id("pr-open:2"), review_id: id("review:1") },
|
||||
Action::OpenStack { request_id: id("pr-open:2"), draft: true },
|
||||
Action::PreparePullRequestPost { request_id: id("pr-post:1"), review_id: id("review:1") },
|
||||
Action::PostPullRequestReview {
|
||||
request_id: id("pr-post:1"),
|
||||
verdict: crate::github::ReviewEvent::RequestChanges,
|
||||
session_revision: 4,
|
||||
},
|
||||
Action::PrepareThreadAnswers {
|
||||
request_id: id("thread-answers:1"),
|
||||
review_id: id("review:1"),
|
||||
},
|
||||
Action::AnswerThreads {
|
||||
request_id: id("thread-answers:1"),
|
||||
review_id: id("review:1"),
|
||||
answers: vec![crate::guided_review::ThreadReply {
|
||||
finding_id: id("finding:1"),
|
||||
reply: Some("Fixed in the last push.".into()),
|
||||
resolve: true,
|
||||
}],
|
||||
},
|
||||
Action::ListGithub { sections: Some(vec![section()]) },
|
||||
Action::SearchGithub { request: 7, section: section(), after: Some("Y3Vyc29yOjMw".into()) },
|
||||
Action::ReadGithubOverview { repository: None, number: 142, pull_request: true },
|
||||
Action::ReadGithubConversation {
|
||||
repository: Some("acme/app".into()),
|
||||
number: 9,
|
||||
pull_request: false,
|
||||
},
|
||||
Action::DraftGithubReply(crate::engine::DraftRequest {
|
||||
request_id: "draft:1".into(),
|
||||
repository: None,
|
||||
number: 142,
|
||||
pull_request: true,
|
||||
target: crate::engine::DraftTarget::Comment(crate::github::ConversationComment {
|
||||
id: "IC_1".into(),
|
||||
author: "mara".into(),
|
||||
bot: false,
|
||||
mine: false,
|
||||
body: "Does this handle Windows paths?".into(),
|
||||
created_at: "2026-08-20T10:00:00Z".into(),
|
||||
url: "https://github.com/acme/app/pull/142#issuecomment-1".into(),
|
||||
}),
|
||||
conversation: Vec::new(),
|
||||
finding: None,
|
||||
note: None,
|
||||
current: None,
|
||||
}),
|
||||
Action::CheckPullRequestFix { number: 142, repository: None },
|
||||
Action::PlanRestack { request_id: id("restack:1") },
|
||||
Action::CheckWorktreeRemoval,
|
||||
Action::LoadFileDiff { request_id: id("file-diff:1"), path: "src/main.rs".into() },
|
||||
Action::ListDirectory {
|
||||
request_id: id("listing:1"),
|
||||
path: "src".into(),
|
||||
include_ignored: false,
|
||||
},
|
||||
Action::ReadProjectFile { request_id: id("file-read:1"), path: "src/main.rs".into() },
|
||||
Action::SetFocus { focused: false },
|
||||
Action::LinkPullRequest { number: 142, url: "https://github.com/acme/app/pull/142".into() },
|
||||
Action::PostGithubComment(crate::engine::GithubPost {
|
||||
repository: None,
|
||||
number: 142,
|
||||
thread: Some("PRRT_1".into()),
|
||||
answering: None,
|
||||
body: "Fixed in the latest push.".into(),
|
||||
}),
|
||||
Action::ChangePullRequest {
|
||||
repository: None,
|
||||
number: 142,
|
||||
write: crate::engine::PullRequestWrite::Merge(crate::github::overview::MergeRequest {
|
||||
method: crate::github::overview::MergeMethod::Squash,
|
||||
head_oid: "a".repeat(40),
|
||||
delete_branch: Some("feat/threads".into()),
|
||||
}),
|
||||
},
|
||||
Action::Restack { request_id: id("restack:1") },
|
||||
Action::Close,
|
||||
]
|
||||
}
|
||||
|
||||
fn section() -> crate::config::GithubSection {
|
||||
crate::config::GithubSection {
|
||||
name: "Mine".into(),
|
||||
query: "is:open is:pr author:@me repo:{repo}".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every wire `Action` pinned to the exact bytes a client writes.
|
||||
///
|
||||
/// The literals were copied from real serializer output, not written from what the types look
|
||||
/// like they ought to emit. That is the whole point: a round-trip exercises both halves of the
|
||||
/// current code, so it passes happily through a renamed field or a retagged variant — which on
|
||||
/// a published protocol is a silent break in every client at once. Changing a string here is
|
||||
/// changing the contract, and `PROTOCOL_VERSION` has to move with it.
|
||||
#[test]
|
||||
fn the_wire_action_vocabulary_is_pinned() {
|
||||
const PINNED: &[&str] = &[
|
||||
r#"{"kind":"submit_user_message","content":{"text":"summarize the diff","images":[{"data":"aGk=","mime":"image/png","name":"shot.png"}]}}"#,
|
||||
r#"{"kind":"steer_turn","content":{"text":"check the windows path too"}}"#,
|
||||
r#"{"kind":"withdraw_steering"}"#,
|
||||
r#"{"kind":"cancel"}"#,
|
||||
r#"{"kind":"edit_resend","content":{"text":"summarize the diff, briefly"}}"#,
|
||||
r#"{"kind":"retry"}"#,
|
||||
r#"{"kind":"regenerate"}"#,
|
||||
r#"{"kind":"respond_permission","content":{"id":"perm:1","reply":"always_persist"}}"#,
|
||||
r#"{"kind":"answer_question","content":{"id":"ask:1","reply":{"answered":["postgres"]}}}"#,
|
||||
r#"{"kind":"set_permission_auto_approve","content":true}"#,
|
||||
r#"{"kind":"select_model","content":{"provider":"anthropic","model":"claude-sonnet-4-20250514"}}"#,
|
||||
r#"{"kind":"set_thinking_level","content":"high"}"#,
|
||||
r#"{"kind":"set_mode","content":"plan"}"#,
|
||||
r#"{"kind":"request_review","content":{"focus":"error handling"}}"#,
|
||||
r#"{"kind":"new_session"}"#,
|
||||
r#"{"kind":"load_session","content":"session-1"}"#,
|
||||
r#"{"kind":"refresh_sessions"}"#,
|
||||
r#"{"kind":"refresh_workspace"}"#,
|
||||
r#"{"kind":"request_context_composition"}"#,
|
||||
r#"{"kind":"compact_now","content":{"focus":"the API decisions"}}"#,
|
||||
r#"{"kind":"load_guided_review","content":{"request_id":"review-load:1","target":{"kind":"working_tree"}}}"#,
|
||||
r#"{"kind":"edit_review","content":{"request_id":"review-save:1","review_id":"review:1","edit":"comment","anchor":{"kind":"line","file_id":"file:1","hunk_id":"hunk:1","side":"new","line":12,"context_hash":""},"severity":"question","title":"","body":"Why does this retry twice?","proposed_fix":null,"send":true}}"#,
|
||||
r#"{"kind":"record_review_progress","content":{"review_id":"review:1","walked_chapter_ids":["chapter:1"]}}"#,
|
||||
r#"{"kind":"record_review_seen","content":{"review_id":"review:1"}}"#,
|
||||
r#"{"kind":"refresh_guided_review","content":{"request_id":"review-load:2","review_id":"review:1","revision_id":"revision:1"}}"#,
|
||||
r#"{"kind":"commit_review_chapters","content":{"request_id":"review-save:2","review_id":"review:1","revision_id":"revision:1","squash":true}}"#,
|
||||
r#"{"kind":"prepare_pull_request","content":{"request_id":"pr-open:1","review_id":"review:1"}}"#,
|
||||
r#"{"kind":"open_pull_request","content":{"request_id":"pr-open:1","title":"Retry once","body":"Why.","draft":false}}"#,
|
||||
r#"{"kind":"prepare_stack","content":{"request_id":"pr-open:2","review_id":"review:1"}}"#,
|
||||
r#"{"kind":"open_stack","content":{"request_id":"pr-open:2","draft":true}}"#,
|
||||
r#"{"kind":"prepare_pull_request_post","content":{"request_id":"pr-post:1","review_id":"review:1"}}"#,
|
||||
r#"{"kind":"post_pull_request_review","content":{"request_id":"pr-post:1","verdict":"request_changes","session_revision":4}}"#,
|
||||
r#"{"kind":"prepare_thread_answers","content":{"request_id":"thread-answers:1","review_id":"review:1"}}"#,
|
||||
r#"{"kind":"answer_threads","content":{"request_id":"thread-answers:1","review_id":"review:1","answers":[{"finding_id":"finding:1","reply":"Fixed in the last push.","resolve":true}]}}"#,
|
||||
r#"{"kind":"list_github","content":{"sections":[{"name":"Mine","query":"is:open is:pr author:@me repo:{repo}"}]}}"#,
|
||||
r#"{"kind":"search_github","content":{"request":7,"section":{"name":"Mine","query":"is:open is:pr author:@me repo:{repo}"},"after":"Y3Vyc29yOjMw"}}"#,
|
||||
r#"{"kind":"read_github_overview","content":{"number":142,"pull_request":true}}"#,
|
||||
r#"{"kind":"read_github_conversation","content":{"repository":"acme/app","number":9,"pull_request":false}}"#,
|
||||
r#"{"kind":"draft_github_reply","content":{"request_id":"draft:1","repository":null,"number":142,"pull_request":true,"target":{"kind":"comment","id":"IC_1","author":"mara","bot":false,"mine":false,"body":"Does this handle Windows paths?","created_at":"2026-08-20T10:00:00Z","url":"https://github.com/acme/app/pull/142#issuecomment-1"},"conversation":[],"finding":null,"note":null,"current":null}}"#,
|
||||
r#"{"kind":"check_pull_request_fix","content":{"number":142}}"#,
|
||||
r#"{"kind":"plan_restack","content":{"request_id":"restack:1"}}"#,
|
||||
r#"{"kind":"check_worktree_removal"}"#,
|
||||
r#"{"kind":"load_file_diff","content":{"request_id":"file-diff:1","path":"src/main.rs"}}"#,
|
||||
r#"{"kind":"list_directory","content":{"request_id":"listing:1","path":"src"}}"#,
|
||||
r#"{"kind":"read_project_file","content":{"request_id":"file-read:1","path":"src/main.rs"}}"#,
|
||||
r#"{"kind":"set_focus","content":{"focused":false}}"#,
|
||||
r#"{"kind":"link_pull_request","content":{"number":142,"url":"https://github.com/acme/app/pull/142"}}"#,
|
||||
r#"{"kind":"post_github_comment","content":{"repository":null,"number":142,"thread":"PRRT_1","answering":null,"body":"Fixed in the latest push."}}"#,
|
||||
r#"{"kind":"change_pull_request","content":{"number":142,"write":{"change":"merge","method":"squash","head_oid":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","delete_branch":"feat/threads"}}}"#,
|
||||
r#"{"kind":"restack","content":{"request_id":"restack:1"}}"#,
|
||||
r#"{"kind":"close"}"#,
|
||||
];
|
||||
let samples = sample_actions();
|
||||
assert_eq!(
|
||||
samples.len(),
|
||||
PINNED.len(),
|
||||
"a wire action has no pinned literal — add one copied from real output"
|
||||
);
|
||||
for (action, pinned) in samples.iter().zip(PINNED) {
|
||||
let tag = action.kind();
|
||||
assert_eq!(
|
||||
serde_json::to_string(action).unwrap().as_str(),
|
||||
*pinned,
|
||||
"{tag} no longer serializes as its published form"
|
||||
);
|
||||
assert_eq!(
|
||||
&serde_json::from_str::<Action>(pinned).unwrap(),
|
||||
action,
|
||||
"{tag} does not read back the form it writes"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `/compact` with no steer is the common case, so a client may omit the payload entirely.
|
||||
#[test]
|
||||
fn compact_now_accepts_a_frame_with_no_focus() {
|
||||
for frame in [
|
||||
r#"{"kind":"compact_now"}"#,
|
||||
r#"{"kind":"compact_now","content":null}"#,
|
||||
r#"{"kind":"compact_now","content":{}}"#,
|
||||
] {
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Action>(frame).expect(frame),
|
||||
Action::CompactNow { focus: None },
|
||||
"{frame}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A bare `list_github` asks for the configured sections, the way the dock's `/github` does.
|
||||
#[test]
|
||||
fn list_github_accepts_a_frame_with_no_sections() {
|
||||
for frame in [
|
||||
r#"{"kind":"list_github"}"#,
|
||||
r#"{"kind":"list_github","content":null}"#,
|
||||
r#"{"kind":"list_github","content":{}}"#,
|
||||
] {
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Action>(frame).expect(frame),
|
||||
Action::ListGithub { sections: None },
|
||||
"{frame}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Exactly the actions that publish to GitHub are writes, and committing is the one write that
|
||||
/// stays local.
|
||||
///
|
||||
/// This is the list `--github-writes` gates, so both directions matter: a write classified as
|
||||
/// a read gets through a session that never opted in, and a read classified as a write is
|
||||
/// refused for no reason. Pinned by kind so the answer cannot drift with the samples.
|
||||
#[test]
|
||||
fn only_publishing_to_github_is_a_github_write() {
|
||||
let writes: Vec<&str> = sample_actions()
|
||||
.iter()
|
||||
.filter(|action| action.writes_to_github())
|
||||
.map(Action::kind)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
writes,
|
||||
[
|
||||
"open_pull_request",
|
||||
"open_stack",
|
||||
"post_pull_request_review",
|
||||
"answer_threads",
|
||||
"post_github_comment",
|
||||
"change_pull_request",
|
||||
"restack",
|
||||
]
|
||||
);
|
||||
let local: Vec<&str> = sample_actions()
|
||||
.iter()
|
||||
.filter(|action| action.writes_the_repository())
|
||||
.map(Action::kind)
|
||||
.collect();
|
||||
assert_eq!(local, ["commit_review_chapters"], "the one local write read-only refuses");
|
||||
assert!(!Action::Other { kind: "merge".into(), content: serde_json::Value::Null }
|
||||
.writes_to_github());
|
||||
}
|
||||
|
||||
/// What a hand-written client leaves out still parses: a comment needs a review, a place and
|
||||
/// words, and every edit kind reads with only what it needs.
|
||||
///
|
||||
/// The break this catches: a field that serializes and so round-trips in the pinned test, but
|
||||
/// that a client never sends, made required by accident.
|
||||
#[test]
|
||||
fn an_edit_needs_only_what_it_is_about() {
|
||||
use crate::engine::ReviewEdit;
|
||||
let parse = |content: serde_json::Value| -> Action {
|
||||
serde_json::from_value(serde_json::json!({ "kind": "edit_review", "content": content }))
|
||||
.unwrap_or_else(|error| panic!("{error}"))
|
||||
};
|
||||
let Action::EditReview { edit: ReviewEdit::Comment { draft, send }, .. } =
|
||||
parse(serde_json::json!({
|
||||
"request_id": "review-save:1", "review_id": "review:1", "edit": "comment",
|
||||
"anchor": { "kind": "line", "file_id": "file:1", "hunk_id": "hunk:1",
|
||||
"side": "new", "line": 3 },
|
||||
"body": "Keep the old value."
|
||||
}))
|
||||
else {
|
||||
panic!("a comment");
|
||||
};
|
||||
assert_eq!(draft.severity, crate::guided_review::FindingSeverity::Issue, "an issue by default");
|
||||
assert!(draft.title.is_empty() && draft.proposed_fix.is_none() && !send);
|
||||
for (edit, extra) in [
|
||||
("reply", serde_json::json!({ "finding_id": "finding:1", "body": "Still wrong." })),
|
||||
("ask_for_fix", serde_json::json!({ "finding_id": "finding:1", "body": "Fix it." })),
|
||||
("resolve", serde_json::json!({ "finding_id": "finding:1" })),
|
||||
("reopen", serde_json::json!({ "finding_id": "finding:1" })),
|
||||
("delete_comment", serde_json::json!({ "finding_id": "finding:1" })),
|
||||
("set_outcome", serde_json::json!({ "outcome": "accepted" })),
|
||||
("send", serde_json::json!({ "finding_ids": ["finding:1"] })),
|
||||
("cancel_send", serde_json::json!({ "submission_id": "submission:1" })),
|
||||
("retry_send", serde_json::json!({ "submission_id": "submission:1" })),
|
||||
] {
|
||||
let mut content = serde_json::json!({
|
||||
"request_id": "review-save:1", "review_id": "review:1", "edit": edit
|
||||
});
|
||||
content.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
assert!(matches!(parse(content), Action::EditReview { .. }), "{edit}");
|
||||
}
|
||||
// Handing a review's comments to a new session is the interface's, not a client's
|
||||
let adopt = serde_json::json!({ "kind": "edit_review", "content": {
|
||||
"request_id": "review-save:1", "review_id": "review:1", "edit": "adopt_carried",
|
||||
"findings": [], "send": false
|
||||
}});
|
||||
assert!(serde_json::from_value::<Action>(adopt).is_err());
|
||||
}
|
||||
|
||||
/// The published kind list is exactly the variants a client can send.
|
||||
///
|
||||
/// [`Action::kind`] is the part the compiler holds; this is what holds [`Action::KINDS`] and
|
||||
/// [`sample_actions`] to it. Without it a variant could be added, given a `kind`, and never
|
||||
/// reach either the published list or the pinned literals — and `luxe-cli`'s translator, which
|
||||
/// cannot match this enum exhaustively across the crate boundary, would never learn of it.
|
||||
/// `other` is excluded on purpose: it is the fallback a client never writes deliberately, and
|
||||
/// `unknown_variants_preserve_the_original_payload` covers it.
|
||||
#[test]
|
||||
fn the_published_kind_list_matches_the_variants() {
|
||||
let sampled: Vec<&str> = sample_actions().iter().map(Action::kind).collect();
|
||||
assert_eq!(sampled, Action::KINDS, "a variant is missing from KINDS or from the samples");
|
||||
assert!(!Action::KINDS.contains(&"other"), "`other` is a fallback, not a client intent");
|
||||
assert_eq!(
|
||||
Action::KINDS.len(),
|
||||
std::collections::BTreeSet::from_iter(Action::KINDS.iter()).len(),
|
||||
"a kind is listed twice"
|
||||
);
|
||||
assert_eq!(
|
||||
Action::kind(&Action::Other { kind: "future".into(), content: serde_json::Value::Null }),
|
||||
"other",
|
||||
"an unknown frame reports the category, not a tag this build invented"
|
||||
);
|
||||
}
|
||||
|
||||
/// A model's display name is what a front-end shows, and falls back to the raw id.
|
||||
///
|
||||
/// Every `state_changed` carries one, so this is a published string, not a UI detail. The break
|
||||
/// it catches: returning the id when an override was set (the picker's chosen label silently
|
||||
/// reverts to `claude-sonnet-4-20250514`), or returning an override that is not there.
|
||||
#[test]
|
||||
fn a_model_shows_its_override_and_falls_back_to_its_id() {
|
||||
let plain = ModelRef::new("anthropic", "claude-sonnet-4-20250514");
|
||||
assert_eq!(plain.display(), "claude-sonnet-4-20250514");
|
||||
|
||||
let labeled = plain.clone().with_display(Some("Claude Sonnet 4".into()));
|
||||
assert_eq!(labeled.display(), "Claude Sonnet 4");
|
||||
assert_eq!(labeled.model, "claude-sonnet-4-20250514", "the label never replaces the id");
|
||||
|
||||
assert_eq!(
|
||||
plain.with_display(None).display(),
|
||||
"claude-sonnet-4-20250514",
|
||||
"clearing the label returns the id, not an empty string"
|
||||
);
|
||||
}
|
||||
|
||||
/// A review failure is classified into the kind a client recovers by, one case per branch.
|
||||
///
|
||||
/// `guided_review_failed` carries this `kind`, and the three mean different things to whoever
|
||||
/// receives them: `unavailable` says retrying will not help, `invalid_target` says the ref was
|
||||
/// wrong, `capture` says the attempt failed and may be worth repeating. Collapsing any two of
|
||||
/// them — which is what deleting either match arm does — tells a client to retry something
|
||||
/// that can never succeed, and no round-trip test would notice.
|
||||
#[test]
|
||||
fn a_review_failure_reports_the_kind_a_client_recovers_by() {
|
||||
use crate::guided_review::{GuidedReviewError, ReviewSourceUnavailable};
|
||||
|
||||
let unavailable = GuidedReviewFailure::from_error(&GuidedReviewError::Unavailable(
|
||||
ReviewSourceUnavailable::MissingTurnBaseline,
|
||||
));
|
||||
assert_eq!(unavailable.kind, GuidedReviewFailureKind::Unavailable);
|
||||
|
||||
let invalid = GuidedReviewFailure::from_error(&GuidedReviewError::InvalidReference {
|
||||
reference: "origin/nope".into(),
|
||||
});
|
||||
assert_eq!(invalid.kind, GuidedReviewFailureKind::InvalidTarget);
|
||||
assert!(invalid.message.contains("origin/nope"), "{}", invalid.message);
|
||||
|
||||
let capture = GuidedReviewFailure::from_error(&GuidedReviewError::MalformedGitOutput {
|
||||
operation: "diff",
|
||||
reason: "unreadable output",
|
||||
});
|
||||
assert_eq!(capture.kind, GuidedReviewFailureKind::Capture, "anything else is a capture");
|
||||
}
|
||||
|
||||
/// A failure message is bounded and stripped of control characters before it reaches the wire.
|
||||
///
|
||||
/// It is built from a subprocess error, so it is the one string here that an attacker-adjacent
|
||||
/// source contributes to. Newlines and tabs survive because a reader needs them; a terminal
|
||||
/// escape does not.
|
||||
#[test]
|
||||
fn a_review_failure_message_cannot_carry_control_characters_or_run_long() {
|
||||
use crate::guided_review::GuidedReviewError;
|
||||
|
||||
let failure = GuidedReviewFailure::from_error(&GuidedReviewError::InvalidReference {
|
||||
reference: format!("\u{1b}[31mred\u{7}\ttab\nline{}", "x".repeat(1_000)),
|
||||
});
|
||||
assert!(!failure.message.contains('\u{1b}'), "an escape sequence reached the wire");
|
||||
assert!(!failure.message.contains('\u{7}'), "a bell reached the wire");
|
||||
assert!(failure.message.contains('\t') && failure.message.contains('\n'));
|
||||
assert_eq!(failure.message.chars().count(), 512, "the message is capped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_reason_roundtrip() {
|
||||
for reason in [StopReason::EndTurn, StopReason::ToolCall, StopReason::Other("timeout".into())] {
|
||||
roundtrip("stop reason", &reason);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_state_roundtrip() {
|
||||
let s = EngineState {
|
||||
model: ModelRef::new("openai", "gpt-4o"),
|
||||
streaming: true,
|
||||
status: "running…".into(),
|
||||
mode: crate::mode::PLAN.into(),
|
||||
thinking: crate::provider::ThinkingLevel::High,
|
||||
};
|
||||
roundtrip("engine state", &s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_state_default_roundtrip() {
|
||||
let s = EngineState::default();
|
||||
roundtrip("engine state default", &s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_state_without_thinking_defaults_off() {
|
||||
let mut value = serde_json::to_value(EngineState::default()).unwrap();
|
||||
value.as_object_mut().unwrap().remove("thinking");
|
||||
let state: EngineState = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(state.thinking, crate::provider::ThinkingLevel::Off);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_token_delta_roundtrip() {
|
||||
let e = Event::TokenDelta { block: 0, delta: "Hello".into() };
|
||||
roundtrip("event token delta", &e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_tool_started_roundtrip() {
|
||||
let e = Event::ToolStarted { call_id: "c1".into(), name: "bash".into() };
|
||||
roundtrip("event tool started", &e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_message_committed_roundtrip() {
|
||||
let message = Message::assistant("I'll help.".to_string());
|
||||
let e = Event::MessageCommitted {
|
||||
session_id: "session-1".into(),
|
||||
entry_id: EntryId("entry-1".into()),
|
||||
message,
|
||||
};
|
||||
roundtrip("event message committed", &e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_remediation_reported_roundtrip() {
|
||||
let report = RemediationReport {
|
||||
review_id: ReviewId::new(),
|
||||
revision_id: ReviewRevisionId::from_canonical_bytes(b"review"),
|
||||
findings: vec![crate::guided_review::RemediationResult {
|
||||
finding_id: crate::guided_review::FindingId::new(),
|
||||
status: crate::guided_review::RemediationStatus::Fixed,
|
||||
note: Some("Added a bound.".into()),
|
||||
}],
|
||||
};
|
||||
roundtrip(
|
||||
"event remediation reported",
|
||||
&Event::RemediationReported { entry_id: EntryId("entry-1".into()), report },
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_review_feedback_turn_dispatched_roundtrip() {
|
||||
roundtrip(
|
||||
"event review feedback turn dispatched",
|
||||
&Event::ReviewFeedbackTurnDispatched { submission_id: SubmissionId::new() },
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_review_feedback_turn_failed_roundtrip() {
|
||||
roundtrip(
|
||||
"event review feedback turn failed",
|
||||
&Event::ReviewFeedbackTurnFailed {
|
||||
submission_id: SubmissionId::new(),
|
||||
message: "provider connection lost".into(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_review_feedback_turn_completed_roundtrip() {
|
||||
roundtrip(
|
||||
"event review feedback turn completed",
|
||||
&Event::ReviewFeedbackTurnCompleted { submission_id: SubmissionId::new() },
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_session_loaded_roundtrip() {
|
||||
let e = Event::SessionLoaded {
|
||||
session_id: "session-1".into(),
|
||||
messages: vec![
|
||||
SessionMessage { entry_id: EntryId("entry-1".into()), message: Message::user("hello") },
|
||||
SessionMessage {
|
||||
entry_id: EntryId("entry-2".into()),
|
||||
message: Message::assistant("hi"),
|
||||
},
|
||||
],
|
||||
};
|
||||
roundtrip("event session loaded", &e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_turn_ended_roundtrip() {
|
||||
let e = Event::TurnEnded { reason: StopReason::EndTurn };
|
||||
roundtrip("event turn ended", &e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_compaction_done_roundtrip() {
|
||||
let e = Event::CompactionDone { tokens_before: 4096, tokens_after: 1024 };
|
||||
roundtrip("event compaction done", &e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_workspace_updated_roundtrip() {
|
||||
let snapshot = WorkspaceSnapshot::empty(
|
||||
crate::workspace::WorkspaceScopeId::new("scope-1"),
|
||||
crate::workspace::ProjectIdentity::non_git("/work/luxe".into(), "luxe", "~/work/luxe"),
|
||||
);
|
||||
roundtrip("event workspace updated", &Event::WorkspaceUpdated(Box::new(snapshot)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_tool_activity_updated_roundtrip() {
|
||||
let activity = ToolActivity::running("session-1", "call-1", "read", "Read Cargo.toml", 42);
|
||||
roundtrip("event tool activity updated", &Event::ToolActivityUpdated(Box::new(activity)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_error_roundtrip() {
|
||||
let e = Event::Error("connection lost".into());
|
||||
roundtrip("event error", &e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_context_usage_roundtrip() {
|
||||
let e = Event::ContextUsage { used_tokens: 12_000, context_window: 128_000 };
|
||||
roundtrip("event context usage", &e);
|
||||
}
|
||||
|
||||
/// The four arms this audit added, round-tripped for payload rather than tag.
|
||||
///
|
||||
/// `every_event_tag_has_a_deserializer_arm` proves a tag is *recognized*; it cannot prove the
|
||||
/// arm carries anything. These two events are the ones a person has to act on — a front-end
|
||||
/// that received them stripped would show an approval prompt with no command in it.
|
||||
#[test]
|
||||
fn the_interactive_events_carry_what_the_user_must_act_on() {
|
||||
let asked = Event::PermissionRequested {
|
||||
id: PermissionRequestId::new(),
|
||||
session_id: "s1".into(),
|
||||
tool: "bash".into(),
|
||||
permission: "bash".into(),
|
||||
summary: "Run: rm -rf build".into(),
|
||||
always_patterns: vec!["rm *".into()],
|
||||
};
|
||||
let decoded: Event = serde_json::from_str(&serde_json::to_string(&asked).unwrap()).unwrap();
|
||||
assert_eq!(decoded, asked, "the approval prompt must survive the wire intact");
|
||||
|
||||
let question = Event::QuestionAsked {
|
||||
id: crate::question::QuestionRequestId::new(),
|
||||
session_id: "s1".into(),
|
||||
prompt: "Which database?".into(),
|
||||
options: Vec::new(),
|
||||
multi: true,
|
||||
};
|
||||
let decoded: Event = serde_json::from_str(&serde_json::to_string(&question).unwrap()).unwrap();
|
||||
assert_eq!(decoded, question);
|
||||
|
||||
// A client reads this one by its fields, so the shape is pinned, not just round-tripped
|
||||
let retrying = Event::ProviderRetrying { attempt: 1, attempts: 3, reason: "busy".into() };
|
||||
assert_eq!(
|
||||
serde_json::to_string(&retrying).unwrap(),
|
||||
r#"{"kind":"provider_retrying","content":{"attempt":1,"attempts":3,"reason":"busy"}}"#
|
||||
);
|
||||
for event in [Event::Notice("heads up".into()), Event::SteeringDelivered { count: 3 }, retrying]
|
||||
{
|
||||
let decoded: Event = serde_json::from_str(&serde_json::to_string(&event).unwrap()).unwrap();
|
||||
assert_eq!(decoded, event);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every variant, sampled, serializes under a tag on the published list and decodes back to the
|
||||
/// same payload; and every published tag has a sample.
|
||||
///
|
||||
/// The break this catches: the list was checked against a hard-coded length and `tag_of` fed it
|
||||
/// one variant, so `provider_retrying` sat in neither and nothing noticed. Now a sampled variant
|
||||
/// missing from the list fails here, and so does an arm that drops its payload.
|
||||
#[test]
|
||||
fn every_event_round_trips_under_a_published_tag() {
|
||||
let samples = samples::every_event();
|
||||
let mut tags: Vec<&str> = samples.iter().map(tag_of).collect();
|
||||
for sample in &samples {
|
||||
let wire = serde_json::to_string(sample).expect("serializes");
|
||||
let decoded = serde_json::from_str::<Event>(&wire);
|
||||
assert_eq!(decoded.as_ref().ok(), Some(sample), "{} lost its payload", tag_of(sample));
|
||||
}
|
||||
tags.sort_unstable();
|
||||
let count = tags.len();
|
||||
tags.dedup();
|
||||
assert_eq!(tags.len(), count, "one sample per variant");
|
||||
let mut published = EVENT_TAGS.to_vec();
|
||||
published.sort_unstable();
|
||||
assert_eq!(tags, published, "the published tags and the sampled variants differ");
|
||||
}
|
||||
224
crates/luxe-core/src/event/tests/decoding.rs
Normal file
224
crates/luxe-core/src/event/tests/decoding.rs
Normal file
@@ -0,0 +1,224 @@
|
||||
//! Decoding — what the derived decoders accept beyond what the serializer writes.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// What a terse sender leaves out still decodes, field by field, the way the hand-written decoders
|
||||
/// read it before the derived ones replaced them.
|
||||
///
|
||||
/// The break this catches: the mirror enums decode only what their attributes say, so a
|
||||
/// `#[serde(default)]` missing there turns a frame a client or an older Luxe sends into an error.
|
||||
/// Every row leaves out a field that is not an `Option`, which decodes as `None` regardless.
|
||||
#[test]
|
||||
fn what_a_sender_may_leave_out_still_decodes() {
|
||||
for action in [
|
||||
r#"{"kind":"list_directory","content":{"request_id":"listing:1"}}"#,
|
||||
r#"{"kind":"commit_review_chapters","content":{"request_id":"review-save:2","review_id":"review:1","revision_id":"revision:1"}}"#,
|
||||
r#"{"kind":"open_pull_request","content":{"request_id":"pr-open:1","title":"Retry once","body":"Why."}}"#,
|
||||
r#"{"kind":"open_stack","content":{"request_id":"pr-open:1"}}"#,
|
||||
] {
|
||||
let decoded = serde_json::from_str::<Action>(action);
|
||||
assert!(!matches!(decoded, Ok(Action::Other { .. }) | Err(_)), "{action}: {decoded:?}");
|
||||
}
|
||||
for event in [
|
||||
r#"{"kind":"token_delta","content":{"delta":"hi"}}"#,
|
||||
r#"{"kind":"thinking_delta","content":{"delta":"hm"}}"#,
|
||||
r#"{"kind":"github_reply_drafted","content":{"request_id":"d:1","body":null,"error":null}}"#,
|
||||
r#"{"kind":"permission_requested","content":{"id":"perm:1","session_id":"s","tool":"bash","permission":"bash","summary":"Run: ls"}}"#,
|
||||
r#"{"kind":"question_asked","content":{"id":"ask:1","session_id":"s","prompt":"Which?"}}"#,
|
||||
r#"{"kind":"review_finished","content":{"verdict":"continue"}}"#,
|
||||
r#"{"kind":"turn_usage","content":{"prompt_tokens":1,"completion_tokens":2,"cost_usd":null}}"#,
|
||||
] {
|
||||
let decoded = serde_json::from_str::<Event>(event);
|
||||
assert!(!matches!(decoded, Ok(Event::Other { .. }) | Err(_)), "{event}: {decoded:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A bare action decodes for exactly the kinds the hand-written decoder took bare: the payload-less
|
||||
/// ones, and the three whose payload is wholly optional.
|
||||
///
|
||||
/// The break this catches: reading no content as `{}` is what lets those three go bare, and it
|
||||
/// would quietly do the same for any other payload whose fields all default.
|
||||
#[test]
|
||||
fn a_bare_action_decodes_only_where_it_always_did() {
|
||||
let bare: Vec<&str> = Action::KINDS
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|kind| serde_json::from_str::<Action>(&format!(r#"{{"kind":"{kind}"}}"#)).is_ok())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
bare,
|
||||
[
|
||||
"withdraw_steering",
|
||||
"cancel",
|
||||
"retry",
|
||||
"regenerate",
|
||||
"request_review",
|
||||
"new_session",
|
||||
"refresh_sessions",
|
||||
"refresh_workspace",
|
||||
"request_context_composition",
|
||||
"compact_now",
|
||||
"list_github",
|
||||
"check_worktree_removal",
|
||||
"close",
|
||||
]
|
||||
);
|
||||
for frame in [r#"{"kind":"request_review"}"#, r#"{"kind":"request_review","content":null}"#] {
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Action>(frame).unwrap(),
|
||||
Action::RequestReview { focus: None },
|
||||
"{frame}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// An event's `"content":null` is not missing content: a payload event refuses it, as it always
|
||||
/// did, even where every field would default.
|
||||
#[test]
|
||||
fn a_null_payload_on_an_event_is_refused() {
|
||||
for frame in
|
||||
[r#"{"kind":"session_usage","content":null}"#, r#"{"kind":"plan_usage","content":null}"#]
|
||||
{
|
||||
assert!(serde_json::from_str::<Event>(frame).is_err(), "{frame}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn action_non_exhaustive_forward_compat() {
|
||||
// A kind chosen not to exist. This test used to name a real candidate (`switch_role`) and
|
||||
// started failing the day that shipped, which proved the guard works and made the test a
|
||||
// hostage to the roadmap.
|
||||
let json = r#"{"kind":"a_variant_from_the_future","anything":"at all"}"#;
|
||||
let decoded: Action = serde_json::from_str(json).expect("should deserialize unknown variant");
|
||||
match decoded {
|
||||
Action::Other { kind, content } => {
|
||||
assert_eq!(kind, "a_variant_from_the_future");
|
||||
assert_eq!(content, serde_json::from_str::<serde_json::Value>(json).unwrap());
|
||||
}
|
||||
_ => panic!("expected Other variant, got something else"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_non_exhaustive_forward_compat() {
|
||||
// Simulate a future variant.
|
||||
let json = r#"{"kind":"session_archived","path":"/tmp/sess.jsonl"}"#;
|
||||
let decoded: Event = serde_json::from_str(json).expect("should deserialize unknown variant");
|
||||
match decoded {
|
||||
Event::Other { kind, content } => {
|
||||
assert_eq!(kind, "session_archived");
|
||||
assert_eq!(content["path"], "/tmp/sess.jsonl");
|
||||
}
|
||||
_ => panic!("expected Other variant, got something else"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A payload-less *event* is accepted empty and refused with content, same as an action.
|
||||
///
|
||||
/// The break this catches: inverting the guard, which would reject the two forms every
|
||||
/// serializer actually emits and accept the one that means a payload was lost.
|
||||
#[test]
|
||||
fn a_payload_less_event_is_accepted_empty_and_refused_with_content() {
|
||||
for form in [
|
||||
r#"{"kind":"workspace_refresh_requested"}"#,
|
||||
r#"{"kind":"workspace_refresh_requested","content":null}"#,
|
||||
r#"{"kind":"workspace_refresh_requested","content":{}}"#,
|
||||
] {
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Event>(form).unwrap(),
|
||||
Event::WorkspaceRefreshRequested,
|
||||
"{form}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
serde_json::from_str::<Event>(
|
||||
r#"{"kind":"workspace_refresh_requested","content":{"scope":"x"}}"#
|
||||
)
|
||||
.is_err(),
|
||||
"content on a payload-less event means something was lost in translation"
|
||||
);
|
||||
}
|
||||
|
||||
/// A payload-less frame is accepted in all three forms a hand-written client produces, and a
|
||||
/// payload on one is still an error rather than something silently dropped.
|
||||
#[test]
|
||||
fn payload_less_frames_are_forgiving_but_not_lax() {
|
||||
for form in [
|
||||
r#"{"kind":"cancel"}"#,
|
||||
r#"{"kind":"cancel","content":null}"#,
|
||||
r#"{"kind":"cancel","content":{}}"#,
|
||||
] {
|
||||
assert_eq!(serde_json::from_str::<Action>(form).unwrap(), Action::Cancel, "{form}");
|
||||
}
|
||||
let error = serde_json::from_str::<Action>(r#"{"kind":"cancel","content":"oops"}"#)
|
||||
.expect_err("content on a payload-less frame is a mistake worth naming");
|
||||
assert!(error.to_string().contains("cancel takes no content"), "{error}");
|
||||
}
|
||||
|
||||
/// A known frame with the wrong payload fails, and the message names the frame.
|
||||
///
|
||||
/// Without the name, a client author gets `missing field `text`` with no way to tell which of
|
||||
/// the three text-carrying frames they got wrong.
|
||||
#[test]
|
||||
fn a_malformed_payload_names_the_frame_it_came_from() {
|
||||
let error = serde_json::from_str::<Action>(r#"{"kind":"steer_turn","content":{}}"#)
|
||||
.expect_err("steer_turn requires text");
|
||||
assert!(error.to_string().starts_with("steer_turn:"), "{error}");
|
||||
|
||||
let error = serde_json::from_str::<Action>(
|
||||
r#"{"kind":"respond_permission","content":{"id":"perm:1"}}"#,
|
||||
)
|
||||
.expect_err("respond_permission requires a reply");
|
||||
assert!(error.to_string().starts_with("respond_permission:"), "{error}");
|
||||
}
|
||||
|
||||
/// A malformed payload is an error, never a panic. The deserializer used to index its content
|
||||
/// map directly (`obj["block"]`), so a truncated or foreign event took the process down
|
||||
/// instead of being rejected — in the one impl whose entire job is to return `Err`.
|
||||
#[test]
|
||||
fn a_malformed_payload_is_rejected_rather_than_fatal() {
|
||||
for malformed in [
|
||||
r#"{"kind":"token_delta","content":{}}"#,
|
||||
r#"{"kind":"tool_started","content":{"call_id":"c1"}}"#,
|
||||
r#"{"kind":"tool_ended","content":{}}"#,
|
||||
r#"{"kind":"context_usage","content":{}}"#,
|
||||
r#"{"kind":"compaction_done","content":{}}"#,
|
||||
r#"{"kind":"turn_ended","content":{}}"#,
|
||||
r#"{"kind":"permission_requested","content":{"id":"x"}}"#,
|
||||
// a count past what its field holds
|
||||
r#"{"kind":"context_usage","content":{"used_tokens":4294967296,"context_window":8}}"#,
|
||||
r#"{"kind":"provider_retrying","content":{"attempt":4294967296,"attempts":3,"reason":"x"}}"#,
|
||||
// loose values the hand-written decoders read as defaults, refused now like any other
|
||||
r#"{"kind":"token_delta","content":{"block":"3","delta":"hi"}}"#,
|
||||
r#"{"kind":"tool_call_composing","content":{"call_id":"c1","name":"bash","subject":5}}"#,
|
||||
] {
|
||||
let decoded = serde_json::from_str::<Event>(malformed);
|
||||
assert!(decoded.is_err(), "{malformed} decoded as {decoded:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every tag the serializer can emit has a variant in the deserializer's mirror enum.
|
||||
///
|
||||
/// `Event` derives `Serialize` from itself but `Deserialize` from a mirror of its variants, and
|
||||
/// an unrecognized tag degrades to [`Event::Other`] rather than failing. Those two facts together
|
||||
/// mean a variant added without its mirror breaks nothing loudly — it just quietly stops arriving
|
||||
/// at the front-end, as `Other`, forever.
|
||||
///
|
||||
/// Content is omitted on purpose: a *known* tag then fails on its missing payload, which is
|
||||
/// fine here. Only an *unknown* tag yields `Other`, so that is the single thing asserted.
|
||||
#[test]
|
||||
fn every_event_tag_has_a_deserializer_arm() {
|
||||
let missing: Vec<&str> = EVENT_TAGS
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|tag| {
|
||||
let decoded = serde_json::from_str::<Event>(&format!(r#"{{"kind":"{tag}"}}"#));
|
||||
matches!(decoded, Ok(Event::Other { .. }))
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
missing.is_empty(),
|
||||
"these variants have no arm in Event's deserializer, so each reaches a front-end as \
|
||||
Other: {missing:?}"
|
||||
);
|
||||
}
|
||||
452
crates/luxe-core/src/event/tests/samples.rs
Normal file
452
crates/luxe-core/src/event/tests/samples.rs
Normal file
@@ -0,0 +1,452 @@
|
||||
//! Samples — one of every `Event` variant, and the table of tags they publish.
|
||||
|
||||
use super::*;
|
||||
use crate::guided_review::{
|
||||
CheckSummary, ReviewBase, ReviewContext, ReviewSessionSaveRequestId, ReviewSource, ReviewStats,
|
||||
SubmissionId,
|
||||
};
|
||||
|
||||
/// One table makes both [`tag_of`] and [`EVENT_TAGS`], so the row the compiler demands for a new
|
||||
/// variant publishes its tag too, and the completeness test then asks for its sample and its arm.
|
||||
macro_rules! published {
|
||||
($($variant:ident => $tag:literal,)*) => {
|
||||
/// The tag every `Event` variant serializes as. A `match`, so it is the compiler that keeps
|
||||
/// it complete: `#[non_exhaustive]` binds other crates, not this one.
|
||||
pub(super) fn tag_of(event: &Event) -> &'static str {
|
||||
match event {
|
||||
$(Event::$variant { .. } => $tag,)*
|
||||
Event::Other { .. } => "other",
|
||||
}
|
||||
}
|
||||
|
||||
/// The tags a client may receive, one per variant but `Other`.
|
||||
pub(super) const EVENT_TAGS: &[&str] = &[$($tag,)*];
|
||||
};
|
||||
}
|
||||
|
||||
published! {
|
||||
TokenDelta => "token_delta",
|
||||
ThinkingDelta => "thinking_delta",
|
||||
ToolCallComposing => "tool_call_composing",
|
||||
ToolStarted => "tool_started",
|
||||
ToolProgress => "tool_progress",
|
||||
ToolCompleted => "tool_completed",
|
||||
ToolEnded => "tool_ended",
|
||||
MessageCommitted => "message_committed",
|
||||
RemediationReported => "remediation_reported",
|
||||
ReviewFeedbackTurnDispatched => "review_feedback_turn_dispatched",
|
||||
ReviewFeedbackTurnFailed => "review_feedback_turn_failed",
|
||||
ReviewQuestionsAnswered => "review_questions_answered",
|
||||
ReviewFeedbackTurnCompleted => "review_feedback_turn_completed",
|
||||
SessionLoaded => "session_loaded",
|
||||
StateChanged => "state_changed",
|
||||
TurnEnded => "turn_ended",
|
||||
LastTurnAvailable => "last_turn_available",
|
||||
CompactionDone => "compaction_done",
|
||||
ContextUsage => "context_usage",
|
||||
TurnUsage => "turn_usage",
|
||||
SessionUsage => "session_usage",
|
||||
PlanUsage => "plan_usage",
|
||||
ContextComposition => "context_composition",
|
||||
ImageAttached => "image_attached",
|
||||
Error => "error",
|
||||
Notice => "notice",
|
||||
PlanWritten => "plan_written",
|
||||
ReviewStarted => "review_started",
|
||||
ReviewFinished => "review_finished",
|
||||
SteeringDelivered => "steering_delivered",
|
||||
ProviderRetrying => "provider_retrying",
|
||||
GuidedReviewLoading => "guided_review_loading",
|
||||
GuidedReviewLoaded => "guided_review_loaded",
|
||||
GuidedReviewGuideUpdated => "guided_review_guide_updated",
|
||||
PullRequestPostPrepared => "pull_request_post_prepared",
|
||||
PullRequestReviewPosted => "pull_request_review_posted",
|
||||
PullRequestPostFailed => "pull_request_post_failed",
|
||||
ThreadAnswersPrepared => "thread_answers_prepared",
|
||||
ThreadsAnswered => "threads_answered",
|
||||
ThreadAnswersFailed => "thread_answers_failed",
|
||||
GithubListed => "github_listed",
|
||||
GithubSearched => "github_searched",
|
||||
GithubOverviewRead => "github_overview_read",
|
||||
GithubConversationRead => "github_conversation_read",
|
||||
GithubCommentPosted => "github_comment_posted",
|
||||
PullRequestChanged => "pull_request_changed",
|
||||
GithubReplyDrafted => "github_reply_drafted",
|
||||
StackPrepared => "stack_prepared",
|
||||
StackOpened => "stack_opened",
|
||||
RestackPlanned => "restack_planned",
|
||||
Restacked => "restacked",
|
||||
RestackFailed => "restack_failed",
|
||||
PullRequestFixChecked => "pull_request_fix_checked",
|
||||
PullRequestPrepared => "pull_request_prepared",
|
||||
PullRequestOpened => "pull_request_opened",
|
||||
PullRequestOpenFailed => "pull_request_open_failed",
|
||||
WorktreeRemovalChecked => "worktree_removal_checked",
|
||||
ReviewCommitted => "review_committed",
|
||||
ReviewCommitFailed => "review_commit_failed",
|
||||
GuidedReviewFailed => "guided_review_failed",
|
||||
FileDiffLoaded => "file_diff_loaded",
|
||||
FileDiffFailed => "file_diff_failed",
|
||||
DirectoryListed => "directory_listed",
|
||||
DirectoryListFailed => "directory_list_failed",
|
||||
ProjectFileRead => "project_file_read",
|
||||
ProjectFileReadFailed => "project_file_read_failed",
|
||||
ReviewSessionRestored => "review_session_restored",
|
||||
ReviewSessionSaved => "review_session_saved",
|
||||
ReviewSessionSaveFailed => "review_session_save_failed",
|
||||
SessionsRefreshed => "sessions_refreshed",
|
||||
WorkspaceRefreshRequested => "workspace_refresh_requested",
|
||||
WorkspaceUpdated => "workspace_updated",
|
||||
TerminalFocusChanged => "terminal_focus_changed",
|
||||
ToolActivityUpdated => "tool_activity_updated",
|
||||
PermissionRequested => "permission_requested",
|
||||
QuestionAsked => "question_asked",
|
||||
Ready => "ready",
|
||||
ActionRejected => "action_rejected",
|
||||
}
|
||||
|
||||
/// An id read from its wire form, so a sample needs no constructor.
|
||||
fn id<T: for<'de> Deserialize<'de>>(literal: &str) -> T {
|
||||
serde_json::from_value(serde_json::json!(literal)).expect("ids are wire strings")
|
||||
}
|
||||
|
||||
fn review() -> GuidedReview {
|
||||
let revision_id = ReviewRevisionId::from_canonical_bytes(b"");
|
||||
GuidedReview {
|
||||
conversation: None,
|
||||
id: id("review:1"),
|
||||
revision_id: revision_id.clone(),
|
||||
target: ReviewTarget::WorkingTree,
|
||||
source: ReviewSource {
|
||||
base: ReviewBase::EmptyTree,
|
||||
content_digest: revision_id,
|
||||
includes_staged: false,
|
||||
includes_unstaged: false,
|
||||
included_untracked_files: 0,
|
||||
captured_at_ms: 0,
|
||||
uncovered_paths: Vec::new(),
|
||||
},
|
||||
context: ReviewContext {
|
||||
title: "No changes".into(),
|
||||
goal: None,
|
||||
phase_index: None,
|
||||
phase_title: None,
|
||||
planning_excerpt: None,
|
||||
acceptance_excerpt: None,
|
||||
source_intent: None,
|
||||
source_commits: 0,
|
||||
pull_request: None,
|
||||
},
|
||||
files: Vec::new(),
|
||||
chapters: Vec::new(),
|
||||
checks: CheckSummary::default(),
|
||||
stats: ReviewStats::default(),
|
||||
generated_at_ms: 0,
|
||||
insight: None,
|
||||
provenance: None,
|
||||
seen: None,
|
||||
brief: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn session() -> Box<ReviewSession> {
|
||||
let review = review();
|
||||
Box::new(ReviewSession::new(review.id, review.target, review.source, 0))
|
||||
}
|
||||
|
||||
fn pull_request() -> crate::github::NewPullRequest {
|
||||
crate::github::NewPullRequest {
|
||||
head: "fix".into(),
|
||||
base: "main".into(),
|
||||
title: "Fix it".into(),
|
||||
body: String::new(),
|
||||
draft: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn section() -> crate::github::ListedSection {
|
||||
crate::github::ListedSection {
|
||||
name: "Mine".into(),
|
||||
items: Vec::new(),
|
||||
error: None,
|
||||
total: None,
|
||||
next: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every variant once, with a payload that has something in it. A variant missing here fails
|
||||
/// `every_event_round_trips_under_a_published_tag`, since its tag is published without a sample.
|
||||
pub(super) fn every_event() -> Vec<Event> {
|
||||
let s = |text: &str| text.to_string();
|
||||
let workspace = WorkspaceSnapshot::empty(
|
||||
crate::workspace::WorkspaceScopeId::new("scope-1"),
|
||||
crate::ProjectIdentity::non_git("/work".into(), "work", "~/work"),
|
||||
);
|
||||
let activity = ToolActivity::running("session-1", "call-1", "read", "Read Cargo.toml", 42);
|
||||
let composition = crate::context_report::ContextComposition {
|
||||
model: s("m"),
|
||||
context_window: 8,
|
||||
used_tokens: 1,
|
||||
calibration: crate::context_report::Calibration::Estimated,
|
||||
slices: Vec::new(),
|
||||
findings: Vec::new(),
|
||||
cache_hit_pct: None,
|
||||
cache_write_pct: None,
|
||||
mcp: None,
|
||||
};
|
||||
let review_failure = |message: &str| GuidedReviewFailure {
|
||||
kind: GuidedReviewFailureKind::Unavailable,
|
||||
message: s(message),
|
||||
};
|
||||
vec![
|
||||
Event::TokenDelta { block: 0, delta: s("hi") },
|
||||
Event::ThinkingDelta { block: 1, delta: s("hm") },
|
||||
Event::ToolCallComposing { call_id: s("c1"), name: s("write"), subject: None, body: None },
|
||||
Event::ToolStarted { call_id: s("c1"), name: s("read") },
|
||||
Event::ToolProgress { call_id: s("c1"), chunk: s("half") },
|
||||
Event::ToolCompleted { call_id: s("c1"), is_error: true, output: s("no") },
|
||||
Event::ToolEnded { call_id: s("c1"), is_error: false },
|
||||
Event::MessageCommitted {
|
||||
session_id: s("s1"),
|
||||
entry_id: crate::session::EntryId(s("e1")),
|
||||
message: crate::Message::assistant("done"),
|
||||
},
|
||||
Event::RemediationReported {
|
||||
entry_id: crate::session::EntryId(s("e1")),
|
||||
report: crate::guided_review::RemediationReport {
|
||||
review_id: id("review:1"),
|
||||
revision_id: ReviewRevisionId::from_canonical_bytes(b""),
|
||||
findings: Vec::new(),
|
||||
},
|
||||
},
|
||||
Event::ReviewFeedbackTurnDispatched { submission_id: SubmissionId::new() },
|
||||
Event::ReviewFeedbackTurnFailed { submission_id: SubmissionId::new(), message: s("x") },
|
||||
Event::ReviewQuestionsAnswered { submission_id: SubmissionId::new(), answer: s("yes") },
|
||||
Event::ReviewFeedbackTurnCompleted { submission_id: SubmissionId::new() },
|
||||
Event::SessionLoaded { session_id: s("s1"), messages: Vec::new() },
|
||||
Event::StateChanged(EngineState::default()),
|
||||
Event::TurnEnded { reason: StopReason::EndTurn },
|
||||
Event::LastTurnAvailable { session_id: s("s1"), turn_id: s("t1") },
|
||||
Event::CompactionDone { tokens_before: 2, tokens_after: 1 },
|
||||
Event::ContextUsage { used_tokens: 1, context_window: 8 },
|
||||
Event::TurnUsage {
|
||||
prompt_tokens: 8,
|
||||
completion_tokens: 2,
|
||||
cost_usd: Some(0.5),
|
||||
cache_read_tokens: 4,
|
||||
cache_write_tokens: 1,
|
||||
reasoning_tokens: 1,
|
||||
source: crate::usage::UsageSource::Review,
|
||||
},
|
||||
Event::SessionUsage(crate::usage::SessionUsage::default()),
|
||||
Event::PlanUsage(crate::provider::PlanUsage::default()),
|
||||
Event::ContextComposition(Box::new(composition)),
|
||||
Event::ImageAttached { mime: s("image/png"), width: 16, height: 9 },
|
||||
Event::Error(s("lost")),
|
||||
Event::Notice(s("heads up")),
|
||||
Event::PlanWritten { path: s("PLAN.md") },
|
||||
Event::ReviewStarted { model: s("m") },
|
||||
Event::ReviewFinished { verdict: RequestedReviewVerdict::Fix, findings: vec![s("f")] },
|
||||
Event::SteeringDelivered { count: 3 },
|
||||
Event::ProviderRetrying { attempt: 1, attempts: 3, reason: s("busy") },
|
||||
Event::GuidedReviewLoading {
|
||||
request_id: ReviewLoadRequestId::new(),
|
||||
target: ReviewTarget::WorkingTree,
|
||||
},
|
||||
Event::GuidedReviewLoaded {
|
||||
request_id: ReviewLoadRequestId::new(),
|
||||
review: Box::new(review()),
|
||||
},
|
||||
Event::GuidedReviewGuideUpdated {
|
||||
request_id: ReviewLoadRequestId::new(),
|
||||
review_id: id("review:1"),
|
||||
revision_id: ReviewRevisionId::from_canonical_bytes(b""),
|
||||
chapters: Vec::new(),
|
||||
provenance: crate::guided_review::GuideProvenance::Model { batches: 2 },
|
||||
brief: None,
|
||||
},
|
||||
Event::PullRequestPostPrepared {
|
||||
request_id: id("pr-post:1"),
|
||||
patches: Vec::new(),
|
||||
head_moved: true,
|
||||
own_pull_request: false,
|
||||
},
|
||||
Event::PullRequestReviewPosted {
|
||||
request_id: id("pr-post:1"),
|
||||
github_review_id: 9,
|
||||
url: s("u"),
|
||||
finding_ids: Vec::new(),
|
||||
},
|
||||
Event::PullRequestPostFailed { request_id: id("pr-post:1"), message: s("x") },
|
||||
Event::ThreadAnswersPrepared {
|
||||
request_id: id("thread-answers:1"),
|
||||
pushed: true,
|
||||
uncommitted: false,
|
||||
},
|
||||
Event::ThreadsAnswered { request_id: id("thread-answers:1"), results: Vec::new() },
|
||||
Event::ThreadAnswersFailed { request_id: id("thread-answers:1"), message: s("x") },
|
||||
Event::GithubListed { repository: Some(s("a/b")), sections: vec![section()] },
|
||||
Event::GithubSearched { request: 7, repository: None, section: section() },
|
||||
Event::GithubOverviewRead {
|
||||
repository: None,
|
||||
number: 1,
|
||||
overview: None,
|
||||
error: Some(s("x")),
|
||||
local: None,
|
||||
},
|
||||
Event::GithubConversationRead { repository: None, number: 1, entries: None, error: None },
|
||||
Event::GithubCommentPosted {
|
||||
repository: None,
|
||||
number: 1,
|
||||
thread: None,
|
||||
url: Some(s("u")),
|
||||
error: None,
|
||||
},
|
||||
Event::PullRequestChanged {
|
||||
repository: None,
|
||||
number: 1,
|
||||
change: None,
|
||||
error: Some(s("x")),
|
||||
},
|
||||
Event::GithubReplyDrafted {
|
||||
request_id: s("r1"),
|
||||
body: Some(s("b")),
|
||||
sources: vec![s("src")],
|
||||
error: None,
|
||||
note: None,
|
||||
},
|
||||
Event::StackPrepared {
|
||||
request_id: id("pr-open:1"),
|
||||
layers: Some(vec![pull_request()]),
|
||||
refusal: None,
|
||||
},
|
||||
Event::StackOpened {
|
||||
request_id: id("pr-open:1"),
|
||||
numbers: vec![1],
|
||||
urls: vec![s("u")],
|
||||
failed: None,
|
||||
},
|
||||
Event::RestackPlanned {
|
||||
request_id: id("restack:1"),
|
||||
plan: None,
|
||||
merged: None,
|
||||
refusal: Some(s("x")),
|
||||
},
|
||||
Event::Restacked {
|
||||
request_id: id("restack:1"),
|
||||
moved: vec![1],
|
||||
retargeted: Vec::new(),
|
||||
retarget_failed: None,
|
||||
},
|
||||
Event::RestackFailed { request_id: id("restack:1"), message: s("x") },
|
||||
Event::PullRequestFixChecked { number: 1, branch: Some(s("b")), refusal: None },
|
||||
Event::PullRequestPrepared {
|
||||
request_id: id("pr-open:1"),
|
||||
pull_request: pull_request(),
|
||||
publication: crate::github::Publication::Ahead { commits: 2 },
|
||||
uncommitted: 1,
|
||||
commits: vec![s("c")],
|
||||
},
|
||||
Event::PullRequestOpened {
|
||||
request_id: id("pr-open:1"),
|
||||
number: 2,
|
||||
url: s("u"),
|
||||
committed: Vec::new(),
|
||||
},
|
||||
Event::PullRequestOpenFailed { request_id: id("pr-open:1"), message: s("x") },
|
||||
Event::WorktreeRemovalChecked { uncommitted: vec![s("a.rs")] },
|
||||
Event::ReviewCommitted {
|
||||
request_id: ReviewSessionSaveRequestId::new(),
|
||||
commits: vec![s("c")],
|
||||
skipped: Vec::new(),
|
||||
},
|
||||
Event::ReviewCommitFailed {
|
||||
request_id: ReviewSessionSaveRequestId::new(),
|
||||
message: s("x"),
|
||||
},
|
||||
Event::GuidedReviewFailed {
|
||||
request_id: ReviewLoadRequestId::new(),
|
||||
target: ReviewTarget::WorkingTree,
|
||||
error: review_failure("gone"),
|
||||
},
|
||||
Event::FileDiffLoaded {
|
||||
request_id: crate::file_diff::FileDiffRequestId::new(),
|
||||
diff: Box::new(crate::file_diff::FileDiff {
|
||||
path: s("a"),
|
||||
file: None,
|
||||
untracked: true,
|
||||
}),
|
||||
},
|
||||
Event::FileDiffFailed {
|
||||
request_id: crate::file_diff::FileDiffRequestId::new(),
|
||||
path: s("a"),
|
||||
error: crate::file_diff::FileDiffFailure::Git(s("x")),
|
||||
},
|
||||
Event::DirectoryListed {
|
||||
request_id: crate::project_files::ListingRequestId::new(),
|
||||
listing: crate::project_files::DirectoryListing {
|
||||
path: s("src"),
|
||||
entries: Vec::new(),
|
||||
omitted: 2,
|
||||
},
|
||||
},
|
||||
Event::DirectoryListFailed {
|
||||
request_id: crate::project_files::ListingRequestId::new(),
|
||||
path: s("src"),
|
||||
error: crate::project_files::ProjectFileFailure::Unreadable(s("x")),
|
||||
},
|
||||
Event::ProjectFileRead {
|
||||
request_id: crate::project_files::FileReadRequestId::new(),
|
||||
file: Box::new(crate::project_files::ProjectFile {
|
||||
path: s("a"),
|
||||
text: s("t"),
|
||||
bytes: 1,
|
||||
truncated: true,
|
||||
binary: false,
|
||||
}),
|
||||
},
|
||||
Event::ProjectFileReadFailed {
|
||||
request_id: crate::project_files::FileReadRequestId::new(),
|
||||
path: s("a"),
|
||||
error: crate::project_files::ProjectFileFailure::NotFound,
|
||||
},
|
||||
Event::ReviewSessionRestored { session: session() },
|
||||
Event::ReviewSessionSaved {
|
||||
request_id: ReviewSessionSaveRequestId::new(),
|
||||
session: session(),
|
||||
},
|
||||
Event::ReviewSessionSaveFailed {
|
||||
request_id: ReviewSessionSaveRequestId::new(),
|
||||
review_id: id("review:1"),
|
||||
message: s("x"),
|
||||
},
|
||||
Event::SessionsRefreshed(vec![s("s1")]),
|
||||
Event::WorkspaceRefreshRequested,
|
||||
Event::WorkspaceUpdated(Box::new(workspace)),
|
||||
Event::TerminalFocusChanged { focused: true },
|
||||
Event::ToolActivityUpdated(Box::new(activity)),
|
||||
Event::PermissionRequested {
|
||||
id: PermissionRequestId::new(),
|
||||
session_id: s("s1"),
|
||||
tool: s("bash"),
|
||||
permission: s("bash"),
|
||||
summary: s("Run"),
|
||||
always_patterns: vec![s("rm *")],
|
||||
},
|
||||
Event::QuestionAsked {
|
||||
id: crate::question::QuestionRequestId::new(),
|
||||
session_id: s("s1"),
|
||||
prompt: s("Which?"),
|
||||
options: Vec::new(),
|
||||
multi: true,
|
||||
},
|
||||
Event::Ready {
|
||||
protocol_version: 1,
|
||||
luxe_version: s("0.1.0"),
|
||||
session_id: s("s1"),
|
||||
cwd: s("/work"),
|
||||
github_writes: true,
|
||||
},
|
||||
Event::ActionRejected { kind: Some(s("x")), reason: s("y") },
|
||||
]
|
||||
}
|
||||
164
crates/luxe-core/src/event/types.rs
Normal file
164
crates/luxe-core/src/event/types.rs
Normal file
@@ -0,0 +1,164 @@
|
||||
//! Event types — the state, identity and failure shapes `Action` and `Event` carry.
|
||||
|
||||
use crate::guided_review::{GuidedReviewError, ReviewSourceUnavailable};
|
||||
use crate::message::Message;
|
||||
use crate::session::EntryId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Model reference — what the agent is speaking through.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ModelRef {
|
||||
/// Provider name (e.g. `openai`, `anthropic`, `gemini`).
|
||||
pub provider: String,
|
||||
/// Model identifier (e.g. `gpt-4o`, `claude-sonnet-4-20250514`).
|
||||
pub model: String,
|
||||
/// Optional human-friendly name for the UI, overriding `model` in display. Cosmetic only.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub display_name: Option<String>,
|
||||
/// Optional override for the API base URL (e.g. a local server).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base_url: Option<String>,
|
||||
}
|
||||
|
||||
impl ModelRef {
|
||||
/// Convenience: build a reference with no base-url override.
|
||||
pub fn new(provider: impl Into<String>, model: impl Into<String>) -> Self {
|
||||
Self { provider: provider.into(), model: model.into(), display_name: None, base_url: None }
|
||||
}
|
||||
|
||||
/// Full builder-style construction.
|
||||
pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
|
||||
self.base_url = Some(url.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Attach an optional UI display name (builder-style).
|
||||
pub fn with_display(mut self, display_name: Option<String>) -> Self {
|
||||
self.display_name = display_name;
|
||||
self
|
||||
}
|
||||
|
||||
/// The name to show in the UI: the `display_name` override when set, else the raw id.
|
||||
pub fn display(&self) -> &str {
|
||||
self.display_name.as_deref().unwrap_or(&self.model)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop reason from a completed LLM turn.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum StopReason {
|
||||
/// The model produced an end-of-turn token (e.g. `<|end|>`).
|
||||
EndTurn,
|
||||
/// The model emitted a tool call and the loop will dispatch it.
|
||||
ToolCall,
|
||||
/// A non-LLM reason (e.g. user cancel, timeout).
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// Engine state snapshot — what the UI should render at this moment.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct EngineState {
|
||||
/// Current active model.
|
||||
pub model: ModelRef,
|
||||
/// Whether a turn is currently in flight.
|
||||
pub streaming: bool,
|
||||
/// Human-readable status message (e.g. "running…", "waiting").
|
||||
pub status: String,
|
||||
/// The mode the session is in (`build`, `plan`).
|
||||
#[serde(default = "default_mode_name")]
|
||||
pub mode: String,
|
||||
/// Current model thinking level.
|
||||
#[serde(default)]
|
||||
pub thinking: crate::provider::ThinkingLevel,
|
||||
}
|
||||
|
||||
impl Default for EngineState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
model: ModelRef::new("unknown", "unknown"),
|
||||
streaming: false,
|
||||
status: "idle".into(),
|
||||
mode: crate::mode::BUILD.into(),
|
||||
thinking: crate::provider::ThinkingLevel::Off,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_mode_name() -> String {
|
||||
crate::mode::BUILD.into()
|
||||
}
|
||||
|
||||
/// What a requested review concluded.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum RequestedReviewVerdict {
|
||||
/// Nothing worth holding the work for
|
||||
Continue,
|
||||
/// Findings, which went back to the agent as a turn
|
||||
Fix,
|
||||
/// No usable review came back; the findings say why
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// One persisted transcript message paired with its session entry identity.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SessionMessage {
|
||||
/// Persisted entry which owns this message.
|
||||
pub entry_id: EntryId,
|
||||
/// Message content stored in that entry.
|
||||
pub message: Message,
|
||||
}
|
||||
|
||||
/// A bounded, serializable failure from immutable Guided Review capture.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct GuidedReviewFailure {
|
||||
/// Broad source category suitable for UI recovery guidance.
|
||||
pub kind: GuidedReviewFailureKind,
|
||||
/// Display-safe, bounded diagnostic detail.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl GuidedReviewFailure {
|
||||
/// Converts a source error without exposing raw diffs or unbounded subprocess output.
|
||||
pub fn from_error(error: &GuidedReviewError) -> Self {
|
||||
let kind = match error {
|
||||
GuidedReviewError::Unavailable(ReviewSourceUnavailable::MissingTurnBaseline)
|
||||
| GuidedReviewError::Unavailable(ReviewSourceUnavailable::ExcludedUntracked {
|
||||
..
|
||||
}) => GuidedReviewFailureKind::Unavailable,
|
||||
GuidedReviewError::InvalidReference { .. } => GuidedReviewFailureKind::InvalidTarget,
|
||||
_ => GuidedReviewFailureKind::Capture,
|
||||
};
|
||||
let message = error
|
||||
.to_string()
|
||||
.chars()
|
||||
.filter(|character| !character.is_control() || matches!(character, '\n' | '\t'))
|
||||
.take(512)
|
||||
.collect::<String>();
|
||||
Self { kind, message }
|
||||
}
|
||||
|
||||
/// The requested target cannot produce a source at all — no retained baseline, no configured
|
||||
/// project root. Unlike [`Self::capture`], retrying the same request will not help.
|
||||
pub fn unavailable(message: impl Into<String>) -> Self {
|
||||
Self { kind: GuidedReviewFailureKind::Unavailable, message: message.into() }
|
||||
}
|
||||
|
||||
/// Capture, parsing, or persistence failed on a target that was otherwise reachable.
|
||||
pub fn capture(message: impl Into<String>) -> Self {
|
||||
Self { kind: GuidedReviewFailureKind::Capture, message: message.into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Broad category for a Guided Review load failure.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GuidedReviewFailureKind {
|
||||
/// The requested target cannot produce a complete source.
|
||||
Unavailable,
|
||||
/// The requested revision or ref was invalid locally.
|
||||
InvalidTarget,
|
||||
/// Local capture, parsing, or persistence failed.
|
||||
Capture,
|
||||
}
|
||||
Reference in New Issue
Block a user