feat(KB-617): add Changes tab to task detail modal for viewing file diffs

- Add baseCommitSha field to tasks for diff computation baseline
- Track modified files in executor and store in database
- Add /api/tasks/:id/diff endpoint to serve unified diffs
- Add getTaskDiff() API client function in dashboard
- Create TaskChangesTab component with file list and diff viewer
- Integrate Changes tab into TaskDetailModal with proper styling
- Add changeset for the new diff viewer feature
This commit is contained in:
gsxdsm
2026-03-31 22:58:38 -07:00
parent 24f68435f6
commit 4ff25d800e
11 changed files with 571 additions and 18 deletions

View File

@@ -0,0 +1,10 @@
---
"@gsxdsm/fusion": minor
---
Add Changes tab to task detail modal showing files modified by the agent and their diffs.
- Track `modifiedFiles` and `baseCommitSha` on tasks during execution
- New API endpoint `GET /tasks/:id/diff` returns file list and patches
- New `TaskChangesTab` component with expandable file diffs
- Changes tab visible for tasks in in-progress, in-review, or done columns

View File

@@ -86,7 +86,7 @@ describe("Database", () => {
}); });
it("seeds schema version", () => { it("seeds schema version", () => {
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
}); });
it("seeds lastModified", () => { it("seeds lastModified", () => {
@@ -109,7 +109,7 @@ describe("Database", () => {
it("is idempotent - calling init() twice does not fail", () => { it("is idempotent - calling init() twice does not fail", () => {
expect(() => db.init()).not.toThrow(); expect(() => db.init()).not.toThrow();
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
}); });
it("does not overwrite existing config on re-init", () => { it("does not overwrite existing config on re-init", () => {
@@ -683,8 +683,8 @@ describe("schema migrations", () => {
// Now run init() which should trigger migration // Now run init() which should trigger migration
db.init(); db.init();
// Verify version bumped to 3 (includes both v1→v2 and v2→v3 migrations) // Verify version bumped to 4 (includes v1→v2, v2→v3, and v3→v4 migrations)
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
// Verify new columns exist and existing data is intact // Verify new columns exist and existing data is intact
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>; const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
@@ -709,11 +709,11 @@ describe("schema migrations", () => {
const db = new Database(kbDir); const db = new Database(kbDir);
db.init(); db.init();
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
// Re-init should not fail // Re-init should not fail
db.init(); db.init();
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
db.close(); db.close();
}); });
@@ -804,11 +804,11 @@ describe("schema migrations", () => {
// Insert a task on the v2 schema // Insert a task on the v2 schema
db.exec(`INSERT INTO tasks (id, description, "column", createdAt, updatedAt) VALUES ('KB-2', 'test v2', 'triage', '2025-01-01', '2025-01-01')`); db.exec(`INSERT INTO tasks (id, description, "column", createdAt, updatedAt) VALUES ('KB-2', 'test v2', 'triage', '2025-01-01', '2025-01-01')`);
// Now run init() which should trigger v2→v3 migration // Now run init() which should trigger migrations v2→v3→v4
db.init(); db.init();
// Verify version bumped to 3 // Verify version bumped to 4
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
// Verify new columns exist and existing data is intact // Verify new columns exist and existing data is intact
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>; const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
@@ -864,7 +864,7 @@ describe("createDatabase factory", () => {
const db = createDatabase(kbDir); const db = createDatabase(kbDir);
db.init(); db.init();
expect(db.getSchemaVersion()).toBe(3); expect(db.getSchemaVersion()).toBe(4);
expect(db.getLastModified()).toBeGreaterThan(0); expect(db.getLastModified()).toBeGreaterThan(0);
db.close(); db.close();

View File

@@ -58,7 +58,7 @@ export function fromJson<T>(json: string | null | undefined): T | undefined {
// ── Schema Definition ──────────────────────────────────────────────── // ── Schema Definition ────────────────────────────────────────────────
const SCHEMA_VERSION = 3; const SCHEMA_VERSION = 4;
const SCHEMA_SQL = ` const SCHEMA_SQL = `
-- Tasks table with JSON columns for nested data -- Tasks table with JSON columns for nested data
@@ -75,6 +75,7 @@ CREATE TABLE IF NOT EXISTS tasks (
blockedBy TEXT, blockedBy TEXT,
paused INTEGER DEFAULT 0, paused INTEGER DEFAULT 0,
baseBranch TEXT, baseBranch TEXT,
baseCommitSha TEXT,
modelPresetId TEXT, modelPresetId TEXT,
modelProvider TEXT, modelProvider TEXT,
modelId TEXT, modelId TEXT,
@@ -99,7 +100,8 @@ CREATE TABLE IF NOT EXISTS tasks (
issueInfo TEXT, issueInfo TEXT,
mergeDetails TEXT, mergeDetails TEXT,
breakIntoSubtasks INTEGER DEFAULT 0, breakIntoSubtasks INTEGER DEFAULT 0,
enabledWorkflowSteps TEXT DEFAULT '[]' enabledWorkflowSteps TEXT DEFAULT '[]',
modifiedFiles TEXT DEFAULT '[]'
); );
-- Config table (single row with project settings) -- Config table (single row with project settings)
@@ -322,6 +324,15 @@ export class Database {
}); });
} }
if (version < 4) {
this.applyMigration(4, () => {
// Add modifiedFiles column to track files changed during agent execution
this.addColumnIfMissing("tasks", "modifiedFiles", "TEXT DEFAULT '[]'");
// Add baseCommitSha column to store the base commit for diff computation
this.addColumnIfMissing("tasks", "baseCommitSha", "TEXT");
});
}
// Future migrations go here: // Future migrations go here:
// if (version < 3) { this.applyMigration(3, () => { ... }); } // if (version < 3) { this.applyMigration(3, () => { ... }); }
} }

View File

@@ -133,6 +133,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
blockedBy: row.blockedBy || undefined, blockedBy: row.blockedBy || undefined,
paused: row.paused ? true : undefined, paused: row.paused ? true : undefined,
baseBranch: row.baseBranch || undefined, baseBranch: row.baseBranch || undefined,
baseCommitSha: row.baseCommitSha || undefined,
modelPresetId: row.modelPresetId || undefined, modelPresetId: row.modelPresetId || undefined,
modelProvider: row.modelProvider || undefined, modelProvider: row.modelProvider || undefined,
modelId: row.modelId || undefined, modelId: row.modelId || undefined,
@@ -157,6 +158,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
mergeDetails: fromJson<import("./types.js").MergeDetails>(row.mergeDetails), mergeDetails: fromJson<import("./types.js").MergeDetails>(row.mergeDetails),
breakIntoSubtasks: row.breakIntoSubtasks ? true : undefined, breakIntoSubtasks: row.breakIntoSubtasks ? true : undefined,
enabledWorkflowSteps: (() => { const e = fromJson<string[]>(row.enabledWorkflowSteps); return e && e.length > 0 ? e : undefined; })(), enabledWorkflowSteps: (() => { const e = fromJson<string[]>(row.enabledWorkflowSteps); return e && e.length > 0 ? e : undefined; })(),
modifiedFiles: (() => { const m = fromJson<string[]>(row.modifiedFiles); return m && m.length > 0 ? m : undefined; })(),
}; };
} }
@@ -167,15 +169,15 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
this.db.prepare(` this.db.prepare(`
INSERT OR REPLACE INTO tasks ( INSERT OR REPLACE INTO tasks (
id, title, description, "column", status, size, reviewLevel, currentStep, id, title, description, "column", status, size, reviewLevel, currentStep,
worktree, blockedBy, paused, baseBranch, modelPresetId, modelProvider, worktree, blockedBy, paused, baseBranch, baseCommitSha, modelPresetId, modelProvider,
modelId, validatorModelProvider, validatorModelId, mergeRetries, error, modelId, validatorModelProvider, validatorModelId, mergeRetries, error,
summary, thinkingLevel, createdAt, updatedAt, columnMovedAt, summary, thinkingLevel, createdAt, updatedAt, columnMovedAt,
dependencies, steps, log, attachments, steeringComments, dependencies, steps, log, attachments, steeringComments,
comments, workflowStepResults, prInfo, issueInfo, mergeDetails, comments, workflowStepResults, prInfo, issueInfo, mergeDetails,
breakIntoSubtasks, enabledWorkflowSteps breakIntoSubtasks, enabledWorkflowSteps, modifiedFiles
) VALUES ( ) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
) )
`).run( `).run(
task.id, task.id,
@@ -190,6 +192,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
task.blockedBy ?? null, task.blockedBy ?? null,
task.paused ? 1 : 0, task.paused ? 1 : 0,
task.baseBranch ?? null, task.baseBranch ?? null,
task.baseCommitSha ?? null,
task.modelPresetId ?? null, task.modelPresetId ?? null,
task.modelProvider ?? null, task.modelProvider ?? null,
task.modelId ?? null, task.modelId ?? null,
@@ -214,6 +217,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
toJsonNullable(task.mergeDetails), toJsonNullable(task.mergeDetails),
task.breakIntoSubtasks ? 1 : 0, task.breakIntoSubtasks ? 1 : 0,
toJson(task.enabledWorkflowSteps || []), toJson(task.enabledWorkflowSteps || []),
toJson(task.modifiedFiles || []),
); );
this.db.bumpLastModified(); this.db.bumpLastModified();
} }
@@ -875,7 +879,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
async updateTask( async updateTask(
id: string, id: string,
updates: { title?: string; description?: string; prompt?: string; worktree?: string; status?: string | null; dependencies?: string[]; blockedBy?: string | null; paused?: boolean; baseBranch?: string; size?: "S" | "M" | "L"; reviewLevel?: number; mergeRetries?: number; modelProvider?: string | null; modelId?: string | null; validatorModelProvider?: string | null; validatorModelId?: string | null; error?: string | null; summary?: string | null; workflowStepResults?: import("./types.js").WorkflowStepResult[] | null }, updates: { title?: string; description?: string; prompt?: string; worktree?: string; status?: string | null; dependencies?: string[]; blockedBy?: string | null; paused?: boolean; baseBranch?: string; baseCommitSha?: string; size?: "S" | "M" | "L"; reviewLevel?: number; mergeRetries?: number; modelProvider?: string | null; modelId?: string | null; validatorModelProvider?: string | null; validatorModelId?: string | null; error?: string | null; summary?: string | null; workflowStepResults?: import("./types.js").WorkflowStepResult[] | null; modifiedFiles?: string[] | null },
): Promise<Task> { ): Promise<Task> {
return this.withTaskLock(id, async () => { return this.withTaskLock(id, async () => {
// Validate that task doesn't depend on itself // Validate that task doesn't depend on itself
@@ -925,6 +929,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
} }
if (updates.paused !== undefined) task.paused = updates.paused || undefined; if (updates.paused !== undefined) task.paused = updates.paused || undefined;
if (updates.baseBranch !== undefined) task.baseBranch = updates.baseBranch; if (updates.baseBranch !== undefined) task.baseBranch = updates.baseBranch;
if (updates.baseCommitSha !== undefined) task.baseCommitSha = updates.baseCommitSha;
if (updates.size !== undefined) task.size = updates.size; if (updates.size !== undefined) task.size = updates.size;
if (updates.reviewLevel !== undefined) task.reviewLevel = updates.reviewLevel; if (updates.reviewLevel !== undefined) task.reviewLevel = updates.reviewLevel;
if (updates.mergeRetries !== undefined) task.mergeRetries = updates.mergeRetries; if (updates.mergeRetries !== undefined) task.mergeRetries = updates.mergeRetries;
@@ -963,6 +968,11 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
} else if (updates.workflowStepResults !== undefined) { } else if (updates.workflowStepResults !== undefined) {
task.workflowStepResults = updates.workflowStepResults; task.workflowStepResults = updates.workflowStepResults;
} }
if (updates.modifiedFiles === null) {
task.modifiedFiles = undefined;
} else if (updates.modifiedFiles !== undefined) {
task.modifiedFiles = updates.modifiedFiles;
}
task.updatedAt = new Date().toISOString(); task.updatedAt = new Date().toISOString();
await this.atomicWriteTaskJson(dir, task); await this.atomicWriteTaskJson(dir, task);
@@ -1465,8 +1475,10 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
breakIntoSubtasks: task.breakIntoSubtasks, breakIntoSubtasks: task.breakIntoSubtasks,
paused: task.paused, paused: task.paused,
baseBranch: task.baseBranch, baseBranch: task.baseBranch,
baseCommitSha: task.baseCommitSha,
mergeRetries: task.mergeRetries, mergeRetries: task.mergeRetries,
error: task.error, error: task.error,
modifiedFiles: task.modifiedFiles,
}; };
// Write to archivedTasks table in SQLite // Write to archivedTasks table in SQLite
@@ -2295,8 +2307,10 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
breakIntoSubtasks: task.breakIntoSubtasks, breakIntoSubtasks: task.breakIntoSubtasks,
paused: task.paused, paused: task.paused,
baseBranch: task.baseBranch, baseBranch: task.baseBranch,
baseCommitSha: task.baseCommitSha,
mergeRetries: task.mergeRetries, mergeRetries: task.mergeRetries,
error: task.error, error: task.error,
modifiedFiles: task.modifiedFiles,
}; };
// Write to archivedTasks table // Write to archivedTasks table
@@ -2359,7 +2373,8 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
validatorModelProvider: entry.validatorModelProvider, validatorModelProvider: entry.validatorModelProvider,
validatorModelId: entry.validatorModelId, validatorModelId: entry.validatorModelId,
breakIntoSubtasks: entry.breakIntoSubtasks, breakIntoSubtasks: entry.breakIntoSubtasks,
// Intentionally NOT restoring: worktree, status, blockedBy, paused, baseBranch, error, steeringComments modifiedFiles: entry.modifiedFiles,
// Intentionally NOT restoring: worktree, status, blockedBy, paused, baseBranch, baseCommitSha, error, steeringComments
}; };
// Write task.json // Write task.json

View File

@@ -387,6 +387,10 @@ export interface Task {
* unmerged branch. The executor reads this to branch from the * unmerged branch. The executor reads this to branch from the
* dependency's branch instead of HEAD. Cleared after worktree creation. */ * dependency's branch instead of HEAD. Cleared after worktree creation. */
baseBranch?: string; baseBranch?: string;
/** Commit SHA of the base branch at worktree creation time.
* Used for computing file diffs when reviewing task changes.
* Set by the executor when creating the worktree. */
baseCommitSha?: string;
attachments?: TaskAttachment[]; attachments?: TaskAttachment[];
steeringComments?: SteeringComment[]; steeringComments?: SteeringComment[];
comments?: TaskComment[]; comments?: TaskComment[];
@@ -428,6 +432,8 @@ export interface Task {
error?: string; error?: string;
/** Optional summary of what was changed/fixed when task is completed */ /** Optional summary of what was changed/fixed when task is completed */
summary?: string; summary?: string;
/** Files modified during agent execution, captured at task completion time */
modifiedFiles?: string[];
/** ISO-8601 timestamp of when the task last entered its current column. /** ISO-8601 timestamp of when the task last entered its current column.
* Used to sort cards within a column so that recently-moved cards appear at the top. */ * Used to sort cards within a column so that recently-moved cards appear at the top. */
columnMovedAt?: string; columnMovedAt?: string;
@@ -861,8 +867,11 @@ export interface ArchivedTaskEntry {
breakIntoSubtasks?: boolean; breakIntoSubtasks?: boolean;
paused?: boolean; paused?: boolean;
baseBranch?: string; baseBranch?: string;
baseCommitSha?: string;
mergeRetries?: number; mergeRetries?: number;
error?: string; error?: string;
/** Files modified during agent execution, captured at task completion time */
modifiedFiles?: string[];
} }
/** Type of planning question presented to the user */ /** Type of planning question presented to the user */

View File

@@ -1868,3 +1868,14 @@ export function fetchProjectTasks(projectId: string, limit?: number, offset?: nu
export function fetchProjectConfig(projectId: string): Promise<{ maxConcurrent: number; rootDir: string }> { export function fetchProjectConfig(projectId: string): Promise<{ maxConcurrent: number; rootDir: string }> {
return api<{ maxConcurrent: number; rootDir: string }>(`/projects/${encodeURIComponent(projectId)}/config`); return api<{ maxConcurrent: number; rootDir: string }>(`/projects/${encodeURIComponent(projectId)}/config`);
} }
/** Diff information for a task */
export interface TaskDiff {
files: string[];
diffs: Record<string, { stat: string; patch: string }>;
}
/** Fetch diff information for a task */
export function fetchTaskDiff(taskId: string): Promise<TaskDiff> {
return api<TaskDiff>(`/tasks/${encodeURIComponent(taskId)}/diff`);
}

View File

@@ -0,0 +1,199 @@
import { useState, useEffect, useCallback } from "react";
import { FileCode, ChevronDown, ChevronRight, AlertCircle } from "lucide-react";
import { fetchTaskDiff, type TaskDiff } from "../api";
interface TaskChangesTabProps {
taskId: string;
worktree?: string;
}
function getFileStatus(file: string, patch: string): "added" | "modified" | "deleted" | "unknown" {
if (patch.includes("diff --git")) {
if (patch.includes("new file mode")) return "added";
if (patch.includes("deleted file mode")) return "deleted";
return "modified";
}
return "unknown";
}
function getStatusColor(status: "added" | "modified" | "deleted" | "unknown"): string {
switch (status) {
case "added":
return "#3fb950"; // green
case "deleted":
return "#f85149"; // red
case "modified":
return "#58a6ff"; // blue
default:
return "#8b949e"; // gray
}
}
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
export function TaskChangesTab({ taskId, worktree }: TaskChangesTabProps) {
const [diffData, setDiffData] = useState<TaskDiff | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [expandedFiles, setExpandedFiles] = useState<Set<string>>(new Set());
const loadDiff = useCallback(async () => {
if (!worktree) {
setLoading(false);
return;
}
try {
setLoading(true);
setError(null);
const data = await fetchTaskDiff(taskId);
setDiffData(data);
// Auto-expand first file if there are files
if (data.files.length > 0) {
setExpandedFiles(new Set([data.files[0]]));
}
} catch (err: any) {
setError(err.message || "Failed to load diff");
} finally {
setLoading(false);
}
}, [taskId, worktree]);
useEffect(() => {
loadDiff();
}, [loadDiff]);
const toggleFile = (file: string) => {
setExpandedFiles((prev) => {
const next = new Set(prev);
if (next.has(file)) {
next.delete(file);
} else {
next.add(file);
}
return next;
});
};
if (loading) {
return (
<div className="detail-section">
<div className="detail-loading">
<div className="loading-spinner" />
<span>Loading changes...</span>
</div>
</div>
);
}
if (error) {
return (
<div className="detail-section">
<div className="detail-error">
<AlertCircle size={16} />
<span>Error loading changes: {error}</span>
</div>
</div>
);
}
if (!worktree) {
return (
<div className="detail-section">
<div className="detail-empty-state">
<FileCode size={24} />
<p>No worktree available for this task.</p>
<span className="detail-empty-hint">
Changes will be shown once the task is in progress.
</span>
</div>
</div>
);
}
if (!diffData || diffData.files.length === 0) {
return (
<div className="detail-section">
<div className="detail-empty-state">
<FileCode size={24} />
<p>No files modified.</p>
<span className="detail-empty-hint">
The agent did not modify any files during execution.
</span>
</div>
</div>
);
}
return (
<div className="detail-section task-changes-tab">
<div className="changes-header">
<h4>
<FileCode size={16} />
Modified Files ({diffData.files.length})
</h4>
<button
className="btn btn-sm"
onClick={loadDiff}
disabled={loading}
>
Refresh
</button>
</div>
<div className="changes-file-list">
{diffData.files.map((file) => {
const fileDiff = diffData.diffs[file];
const status = getFileStatus(file, fileDiff?.patch || "");
const isExpanded = expandedFiles.has(file);
return (
<div
key={file}
className={`changes-file-item ${isExpanded ? "expanded" : ""}`}
>
<button
className="changes-file-header"
onClick={() => toggleFile(file)}
>
<span className="changes-file-toggle">
{isExpanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
</span>
<span
className="changes-file-status"
style={{ color: getStatusColor(status) }}
title={status}
>
{status === "added" && "A"}
{status === "modified" && "M"}
{status === "deleted" && "D"}
{status === "unknown" && "?"}
</span>
<span className="changes-file-path" title={file}>
{file}
</span>
{fileDiff?.stat && (
<span className="changes-file-stat" title={fileDiff.stat}>
{fileDiff.stat}
</span>
)}
</button>
{isExpanded && fileDiff?.patch && (
<div className="changes-file-content">
<pre className="changes-diff-patch">
<code>{fileDiff.patch}</code>
</pre>
</div>
)}
</div>
);
})}
</div>
</div>
);
}

View File

@@ -13,6 +13,7 @@ import { ModelSelectorTab } from "./ModelSelectorTab";
import { PrSection } from "./PrSection"; import { PrSection } from "./PrSection";
import { TaskComments } from "./TaskComments"; import { TaskComments } from "./TaskComments";
import { MergeDetails } from "./MergeDetails"; import { MergeDetails } from "./MergeDetails";
import { TaskChangesTab } from "./TaskChangesTab";
interface ModelSelection { interface ModelSelection {
provider?: string; provider?: string;
@@ -105,7 +106,7 @@ export function TaskDetailModal({
addToast, addToast,
githubTokenConfigured, githubTokenConfigured,
}: TaskDetailModalProps) { }: TaskDetailModalProps) {
const [activeTab, setActiveTab] = useState<"definition" | "activity" | "agent-log" | "steering" | "comments" | "model">("definition"); const [activeTab, setActiveTab] = useState<"definition" | "activity" | "agent-log" | "changes" | "steering" | "comments" | "model">("definition");
const [attachments, setAttachments] = useState<TaskAttachment[]>(task.attachments || []); const [attachments, setAttachments] = useState<TaskAttachment[]>(task.attachments || []);
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const [dependencies, setDependencies] = useState<string[]>(task.dependencies || []); const [dependencies, setDependencies] = useState<string[]>(task.dependencies || []);
@@ -671,6 +672,14 @@ export function TaskDetailModal({
> >
Agent Log Agent Log
</button> </button>
{(task.column === "in-progress" || task.column === "in-review" || task.column === "done") && (
<button
className={`detail-tab${activeTab === "changes" ? " detail-tab-active" : ""}`}
onClick={() => setActiveTab("changes")}
>
Changes
</button>
)}
<button <button
className={`detail-tab${activeTab === "steering" ? " detail-tab-active" : ""}`} className={`detail-tab${activeTab === "steering" ? " detail-tab-active" : ""}`}
onClick={() => setActiveTab("steering")} onClick={() => setActiveTab("steering")}
@@ -703,6 +712,8 @@ export function TaskDetailModal({
validatorModel={getValidatorSelection(task)} validatorModel={getValidatorSelection(task)}
/> />
</div> </div>
) : activeTab === "changes" ? (
<TaskChangesTab taskId={task.id} worktree={task.worktree} />
) : activeTab === "steering" ? ( ) : activeTab === "steering" ? (
<SteeringTab task={task} addToast={addToast} /> <SteeringTab task={task} addToast={addToast} />
) : activeTab === "comments" ? ( ) : activeTab === "comments" ? (

View File

@@ -11812,3 +11812,134 @@ html .column.drag-over * {
[data-theme="light"] .gm-load-more:hover { [data-theme="light"] .gm-load-more:hover {
background: rgba(0, 0, 0, 0.03); background: rgba(0, 0, 0, 0.03);
} }
/* ── Task Changes Tab Styles ─────────────────────────────────────────────── */
.task-changes-tab {
padding: 16px;
}
.changes-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
}
.changes-header h4 {
margin: 0;
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 500;
}
.changes-file-list {
border: 1px solid var(--border, #30363d);
border-radius: 8px;
overflow: hidden;
}
.changes-file-item {
border-bottom: 1px solid var(--border, #30363d);
}
.changes-file-item:last-child {
border-bottom: none;
}
.changes-file-item.expanded {
background: var(--bg-secondary, #161b22);
}
.changes-file-header {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
background: none;
border: none;
width: 100%;
text-align: left;
cursor: pointer;
color: var(--text-primary, #c9d1d9);
font-size: 13px;
transition: background 0.15s;
}
.changes-file-header:hover {
background: var(--bg-hover, #1f242c);
}
.changes-file-toggle {
display: flex;
align-items: center;
color: var(--text-secondary, #8b949e);
flex-shrink: 0;
}
.changes-file-status {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
flex-shrink: 0;
}
.changes-file-path {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
}
.changes-file-stat {
color: var(--text-secondary, #8b949e);
font-size: 11px;
flex-shrink: 0;
margin-left: 8px;
}
.changes-file-content {
border-top: 1px solid var(--border, #30363d);
background: var(--bg-primary, #0d1117);
}
.changes-diff-patch {
margin: 0;
padding: 12px;
font-size: 12px;
line-height: 1.5;
overflow-x: auto;
white-space: pre;
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
color: var(--text-primary, #c9d1d9);
}
.changes-diff-patch code {
background: none;
padding: 0;
}
/* Syntax highlighting for diff */
.changes-diff-patch .diff-add,
.changes-diff-patch [data-prefix="+"] {
color: #3fb950;
}
.changes-diff-patch .diff-del,
.changes-diff-patch [data-prefix="-"] {
color: #f85149;
}
.changes-diff-patch .diff-hunk,
.changes-diff-patch [data-prefix="@@"] {
color: #58a6ff;
}

View File

@@ -1841,6 +1841,82 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
} }
}); });
/**
* GET /api/tasks/:id/diff
* Get detailed diff information for files modified during task execution.
* Returns: { files: string[]; diffs: Record<string, { stat: string; patch: string }> }
*/
router.get("/tasks/:id/diff", async (req, res) => {
try {
const task = await store.getTask(req.params.id);
// Only tasks with worktrees can have diffs
if (!task.worktree || !existsSync(task.worktree)) {
res.json({ files: [], diffs: {} });
return;
}
// Use stored modifiedFiles if available, otherwise compute on-the-fly
let files = task.modifiedFiles;
if (!files || files.length === 0) {
// Fallback: compute files using git diff
try {
const baseRef = task.baseCommitSha ?? "HEAD~1";
const output = execSync(`git diff --name-only ${baseRef}..HEAD`, {
cwd: task.worktree,
encoding: "utf-8",
timeout: 5000,
}).trim();
files = output ? output.split("\n").filter(Boolean) : [];
} catch {
files = [];
}
}
if (files.length === 0) {
res.json({ files: [], diffs: {} });
return;
}
// Compute diffs for each file
const diffs: Record<string, { stat: string; patch: string }> = {};
const baseRef = task.baseCommitSha ?? "HEAD~1";
for (const file of files) {
try {
// Get stat for this file
const stat = execSync(`git diff --stat ${baseRef}..HEAD -- "${file}"`, {
cwd: task.worktree,
encoding: "utf-8",
timeout: 5000,
}).trim();
// Get patch for this file
const patch = execSync(`git diff ${baseRef}..HEAD -- "${file}"`, {
cwd: task.worktree,
encoding: "utf-8",
timeout: 10000,
});
diffs[file] = { stat, patch };
} catch (err: any) {
// Log error but continue with other files
console.warn(`Failed to get diff for ${file}:`, err.message);
diffs[file] = { stat: "", patch: "" };
}
}
res.json({ files, diffs });
} catch (err: any) {
if (err.code === "ENOENT") {
res.status(404).json({ error: `Task ${req.params.id} not found` });
} else {
res.status(500).json({ error: err.message || "Internal server error" });
}
}
});
/** /**
* GET /api/tasks/:id/workflow-results * GET /api/tasks/:id/workflow-results
* Get workflow step execution results for a task. * Get workflow step execution results for a task.

View File

@@ -457,6 +457,23 @@ export class TaskExecutor {
worktreePath = await this.createWorktree(branchName, worktreePath, task.id); worktreePath = await this.createWorktree(branchName, worktreePath, task.id);
} }
// Capture the base commit SHA for diff computation
// This is done after worktree creation when we're on the new branch
if (!task.baseCommitSha) {
try {
const baseCommitSha = execSync("git rev-parse HEAD", {
cwd: worktreePath,
stdio: "pipe",
encoding: "utf-8",
}).trim();
await this.store.updateTask(task.id, { baseCommitSha });
executorLog.log(`${task.id}: captured baseCommitSha ${baseCommitSha.slice(0, 7)}`);
} catch (err: any) {
executorLog.log(`Failed to capture baseCommitSha for ${task.id}: ${err.message}`);
// Non-fatal: task can continue without baseCommitSha
}
}
this.activeWorktrees.set(task.id, worktreePath); this.activeWorktrees.set(task.id, worktreePath);
this.options.onStart?.(task, worktreePath); this.options.onStart?.(task, worktreePath);
@@ -571,6 +588,14 @@ export class TaskExecutor {
} }
if (taskDone) { if (taskDone) {
// Capture modified files before running workflow steps
const updatedTask = await this.store.getTask(task.id);
const modifiedFiles = this.captureModifiedFiles(worktreePath, updatedTask.baseCommitSha);
if (modifiedFiles.length > 0) {
await this.store.updateTask(task.id, { modifiedFiles });
executorLog.log(`${task.id}: captured ${modifiedFiles.length} modified files`);
}
// Run workflow steps before moving to in-review // Run workflow steps before moving to in-review
const workflowSuccess = await this.runWorkflowSteps(task, worktreePath, settings); const workflowSuccess = await this.runWorkflowSteps(task, worktreePath, settings);
if (!workflowSuccess) { if (!workflowSuccess) {
@@ -1067,6 +1092,61 @@ export class TaskExecutor {
await this.store.logEntry(taskId, "Execution stopped — work discarded, moved to triage for re-specification"); await this.store.logEntry(taskId, "Execution stopped — work discarded, moved to triage for re-specification");
} }
/**
* Capture the list of files modified during agent execution.
* Uses git diff against the stored baseCommitSha to determine what changed.
* Returns an empty array if no changes or if git commands fail.
*/
private captureModifiedFiles(worktreePath: string, baseCommitSha?: string): string[] {
try {
// Determine the base reference for diff
// If baseCommitSha is stored, use it; otherwise fall back to merge-base with HEAD
let baseRef = baseCommitSha;
if (!baseRef) {
// Try to find merge-base with main/master as fallback
try {
baseRef = execSync("git merge-base HEAD origin/main 2>/dev/null || git merge-base HEAD main", {
cwd: worktreePath,
stdio: "pipe",
encoding: "utf-8",
}).trim();
} catch {
// If merge-base fails, use HEAD~1 as last resort
try {
baseRef = execSync("git rev-parse HEAD~1", {
cwd: worktreePath,
stdio: "pipe",
encoding: "utf-8",
}).trim();
} catch {
executorLog.log(`Could not determine base commit for diff in ${worktreePath}`);
return [];
}
}
}
if (!baseRef) {
return [];
}
// Get list of modified files using git diff --name-only
const output = execSync(`git diff --name-only ${baseRef}..HEAD`, {
cwd: worktreePath,
stdio: "pipe",
encoding: "utf-8",
}).trim();
if (!output) {
return [];
}
return output.split("\n").filter(Boolean);
} catch (err: any) {
executorLog.log(`Failed to capture modified files: ${err.message}`);
return [];
}
}
// ── Worktree management ──────────────────────────────────────────── // ── Worktree management ────────────────────────────────────────────
/** /**