mirror of
https://github.com/davidkaya/aryx.git
synced 2026-07-24 05:28:46 +02:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3e611dc74 | ||
|
|
dcabc65dbf | ||
|
|
1068ed39e4 | ||
|
|
e956f8ea6c |
@@ -137,6 +137,18 @@ jobs:
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
write_github_env() {
|
||||
local name="$1"
|
||||
local value="$2"
|
||||
local delimiter
|
||||
delimiter="ARYX_ENV_$(uuidgen | tr '[:lower:]' '[:upper:]')"
|
||||
{
|
||||
printf '%s<<%s\n' "$name" "$delimiter"
|
||||
printf '%s\n' "$value"
|
||||
printf '%s\n' "$delimiter"
|
||||
} >> "$GITHUB_ENV"
|
||||
}
|
||||
|
||||
if [[ -z "$APPLE_CERT_P12_BASE64" ]]; then
|
||||
echo "Missing required secret: APPLE_CERT_P12_BASE64" >&2
|
||||
exit 1
|
||||
@@ -162,18 +174,92 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SOURCE_CERT_PATH="$RUNNER_TEMP/apple-signing-source.p12"
|
||||
CERT_PATH="$RUNNER_TEMP/apple-signing.p12"
|
||||
PEM_PATH="$RUNNER_TEMP/apple-signing.pem"
|
||||
PRECHECK_KEYCHAIN_PATH="$RUNNER_TEMP/apple-signing-preflight.keychain-db"
|
||||
PRECHECK_KEYCHAIN_PASSWORD="$(uuidgen)"
|
||||
API_KEY_PATH="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
|
||||
|
||||
echo "$APPLE_CERT_P12_BASE64" | base64 --decode > "$CERT_PATH"
|
||||
cleanup_precheck_keychain() {
|
||||
security delete-keychain "$PRECHECK_KEYCHAIN_PATH" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
trap cleanup_precheck_keychain EXIT
|
||||
|
||||
CERT_PATH="$SOURCE_CERT_PATH" python3 - <<'PY'
|
||||
import base64
|
||||
import binascii
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
raw_value = os.environ["APPLE_CERT_P12_BASE64"]
|
||||
normalized_value = "".join(raw_value.split())
|
||||
if not normalized_value:
|
||||
raise SystemExit("APPLE_CERT_P12_BASE64 is empty after whitespace normalization")
|
||||
|
||||
try:
|
||||
decoded = base64.b64decode(normalized_value, validate=True)
|
||||
except binascii.Error:
|
||||
raise SystemExit("APPLE_CERT_P12_BASE64 is not valid base64")
|
||||
|
||||
if not decoded:
|
||||
raise SystemExit("Decoded Apple signing certificate is empty")
|
||||
|
||||
Path(os.environ["CERT_PATH"]).write_bytes(decoded)
|
||||
PY
|
||||
printf '%s' "$APPLE_API_KEY_P8" > "$API_KEY_PATH"
|
||||
|
||||
echo "CSC_LINK=$CERT_PATH" >> "$GITHUB_ENV"
|
||||
echo "CSC_KEY_PASSWORD=$APPLE_CERT_PASSWORD" >> "$GITHUB_ENV"
|
||||
echo "APPLE_API_KEY=$API_KEY_PATH" >> "$GITHUB_ENV"
|
||||
echo "APPLE_API_KEY_ID=$APPLE_API_KEY_ID" >> "$GITHUB_ENV"
|
||||
echo "APPLE_API_ISSUER=$APPLE_API_ISSUER" >> "$GITHUB_ENV"
|
||||
echo "APPLE_TEAM_ID=$APPLE_TEAM_ID" >> "$GITHUB_ENV"
|
||||
if [[ ! -s "$SOURCE_CERT_PATH" ]]; then
|
||||
echo "Decoded Apple signing certificate file is empty." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! openssl pkcs12 -in "$SOURCE_CERT_PATH" -noout -passin env:APPLE_CERT_PASSWORD >/dev/null 2>&1; then
|
||||
echo "Decoded Apple signing certificate could not be opened with APPLE_CERT_PASSWORD." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! openssl pkcs12 -in "$SOURCE_CERT_PATH" -passin env:APPLE_CERT_PASSWORD -nodes -out "$PEM_PATH" >/dev/null 2>&1; then
|
||||
echo "Decoded Apple signing certificate could not be converted to PEM." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! openssl pkcs12 -export -out "$CERT_PATH" -in "$PEM_PATH" -passout env:APPLE_CERT_PASSWORD -macalg sha1 -keypbe PBE-SHA1-3DES -certpbe PBE-SHA1-3DES >/dev/null 2>&1; then
|
||||
echo "Apple signing certificate could not be re-exported into a macOS-compatible PKCS#12." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -s "$CERT_PATH" ]]; then
|
||||
echo "Normalized Apple signing certificate file is empty." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! security create-keychain -p "$PRECHECK_KEYCHAIN_PASSWORD" "$PRECHECK_KEYCHAIN_PATH" >/dev/null 2>&1; then
|
||||
echo "Unable to create the macOS signing precheck keychain." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! security unlock-keychain -p "$PRECHECK_KEYCHAIN_PASSWORD" "$PRECHECK_KEYCHAIN_PATH" >/dev/null 2>&1; then
|
||||
echo "Unable to unlock the macOS signing precheck keychain." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! security import "$CERT_PATH" -k "$PRECHECK_KEYCHAIN_PATH" -P "$APPLE_CERT_PASSWORD" -T /usr/bin/codesign -T /usr/bin/productsign >/dev/null 2>&1; then
|
||||
echo "Normalized Apple signing certificate is still not importable by macOS security." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
rm -f "$SOURCE_CERT_PATH" "$PEM_PATH"
|
||||
cleanup_precheck_keychain
|
||||
trap - EXIT
|
||||
|
||||
write_github_env "CSC_LINK" "$CERT_PATH"
|
||||
write_github_env "CSC_KEY_PASSWORD" "$APPLE_CERT_PASSWORD"
|
||||
write_github_env "APPLE_API_KEY" "$API_KEY_PATH"
|
||||
write_github_env "APPLE_API_KEY_ID" "$APPLE_API_KEY_ID"
|
||||
write_github_env "APPLE_API_ISSUER" "$APPLE_API_ISSUER"
|
||||
write_github_env "APPLE_TEAM_ID" "$APPLE_TEAM_ID"
|
||||
|
||||
- name: Build and publish release artifacts
|
||||
env:
|
||||
|
||||
+3
-1
@@ -220,6 +220,8 @@ The protocol also carries **turn-scoped lifecycle events** alongside output delt
|
||||
|
||||
These events flow through a single `onTurnScopedEvent` callback on the `runTurn` command, avoiding per-event-type callback proliferation. The main process maps each event to a `SessionEventRecord` and pushes it to the renderer, where lightweight state maps (activity, usage, turn-event log) consume them without touching the persisted workspace.
|
||||
|
||||
Tool-call activity records can also be enriched with a stable `toolCallId` and aggregated file-change preview payloads (`path`, unified diff, and optional new-file contents). The sidecar derives those previews from Copilot SDK write permission requests, and the main process merges repeated write events by `toolCallId` into the persisted run timeline so future UI surfaces can render file previews without reinterpreting approval payloads.
|
||||
|
||||
The same boundary also supports server-scoped sidecar commands that do not require a live Copilot session. The new `get-quota` command uses the SDK's `account.getQuota` RPC to fetch account quota snapshots on demand, then returns them as a `quota-result` protocol event followed by the usual `command-complete` sentinel.
|
||||
|
||||
For project-backed sessions, the sidecar also discovers GitHub Copilot CLI hook definitions from `.github/hooks/*.json` under the repository root. Those files are parsed and merged once per run bundle, then projected onto the SDK session hook delegates. Hook commands run synchronously in the sidecar through the platform shell, with stdin JSON payloads shaped to match Copilot CLI hook expectations as closely as the SDK allows. Hook failures are logged to stderr and treated as non-fatal diagnostics, while `preToolUse` hook outputs can still deny a tool call before Aryx falls back to its built-in approval policy.
|
||||
@@ -346,7 +348,7 @@ The build pipeline is organized around three layers:
|
||||
- publishing the sidecar for the target runtime
|
||||
- packaging platform artifacts with electron-builder
|
||||
|
||||
electron-builder bundles the packaged Electron app, copies the published sidecar into `resources/sidecar`, produces Windows NSIS installers, macOS DMG + ZIP artifacts, and Linux AppImages, and uploads the release assets plus update metadata to GitHub Releases. Tagged macOS release jobs now materialize the certificate and App Store Connect key from repository secrets into temporary files on the runner, export the standard `electron-builder` signing and notarization environment variables from those files, and package with checked-in hardened-runtime entitlements so native modules still run correctly under code signing. The main process consumes the published metadata through `electron-updater`, which checks GitHub Releases for packaged builds and can stage a restart-based update install.
|
||||
electron-builder bundles the packaged Electron app, copies the published sidecar into `resources/sidecar`, produces Windows NSIS installers, macOS DMG + ZIP artifacts, and Linux AppImages, and uploads the release assets plus update metadata to GitHub Releases. Tagged macOS release jobs now materialize the certificate and App Store Connect key from repository secrets into temporary files on the runner, normalize the decoded PKCS#12 into a `security import`-compatible container, preflight that normalized certificate against a temporary keychain, export the standard `electron-builder` signing and notarization environment variables from those files, and package with checked-in hardened-runtime entitlements so native modules still run correctly under code signing. The main process consumes the published metadata through `electron-updater`, which checks GitHub Releases for packaged builds and can stage a restart-based update install.
|
||||
|
||||
Current Windows builds are unsigned, so the packaging config disables executable resource editing/signing and skips Windows update signature verification until a code-signing certificate is available. The packaging scripts also clear `release/` before each build so local packaging runs cannot accidentally mix stale artifacts with current ones.
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ To publish packaged artifacts and update metadata to GitHub Releases, run:
|
||||
|
||||
GitHub Actions runs validation on pushes and pull requests, and tagged releases now use `electron-builder` to publish Windows (NSIS), macOS (DMG + ZIP for updater metadata), and Linux (AppImage) artifacts directly to GitHub Releases. Packaged builds use `electron-updater` against those releases for in-app updates.
|
||||
|
||||
Tagged macOS release jobs now prepare signing assets from the GitHub secrets `APPLE_CERT_P12_BASE64`, `APPLE_CERT_PASSWORD`, `APPLE_API_KEY_P8`, `APPLE_API_KEY_ID`, `APPLE_API_ISSUER`, and `APPLE_TEAM_ID`, then export the standard `electron-builder` environment variables (`CSC_LINK`, `CSC_KEY_PASSWORD`, `APPLE_API_KEY`, `APPLE_API_KEY_ID`, `APPLE_API_ISSUER`, `APPLE_TEAM_ID`) before packaging. That same release path signs and notarizes the macOS artifacts as part of publication.
|
||||
Tagged macOS release jobs now prepare signing assets from the GitHub secrets `APPLE_CERT_P12_BASE64`, `APPLE_CERT_PASSWORD`, `APPLE_API_KEY_P8`, `APPLE_API_KEY_ID`, `APPLE_API_ISSUER`, and `APPLE_TEAM_ID`, normalize the decoded PKCS#12 into a macOS-compatible container, preflight `security import` against a temporary keychain, and then export the standard `electron-builder` environment variables (`CSC_LINK`, `CSC_KEY_PASSWORD`, `APPLE_API_KEY`, `APPLE_API_KEY_ID`, `APPLE_API_ISSUER`, `APPLE_TEAM_ID`) before packaging. That same release path signs and notarizes the macOS artifacts as part of publication.
|
||||
|
||||
Windows builds are currently packaged without Authenticode signing, so Aryx disables `electron-updater`'s Windows signature verification until a signing certificate is configured. macOS auto-update metadata still requires a ZIP artifact alongside the DMG build.
|
||||
|
||||
|
||||
@@ -340,6 +340,8 @@ public sealed class AgentActivityEventDto : SidecarEventDto
|
||||
public string? SourceAgentId { get; init; }
|
||||
public string? SourceAgentName { get; init; }
|
||||
public string? ToolName { get; init; }
|
||||
public string? ToolCallId { get; init; }
|
||||
public IReadOnlyList<ToolCallFileChangeDto>? FileChanges { get; init; }
|
||||
}
|
||||
|
||||
public sealed class SubagentEventDto : SidecarEventDto
|
||||
@@ -503,6 +505,13 @@ public sealed class PermissionDetailDto
|
||||
public string? HookMessage { get; init; }
|
||||
}
|
||||
|
||||
public sealed class ToolCallFileChangeDto
|
||||
{
|
||||
public string Path { get; init; } = string.Empty;
|
||||
public string? Diff { get; init; }
|
||||
public string? NewFileContents { get; init; }
|
||||
}
|
||||
|
||||
public sealed class ApprovalRequestedEventDto : SidecarEventDto
|
||||
{
|
||||
public string SessionId { get; init; } = string.Empty;
|
||||
|
||||
@@ -19,6 +19,7 @@ internal sealed class CopilotApprovalCoordinator
|
||||
private const string MemoryPermissionKind = "memory";
|
||||
private const string CustomToolPermissionKind = "custom-tool";
|
||||
private const string HookPermissionKind = "hook";
|
||||
private const string ToolCallingActivityType = "tool-calling";
|
||||
|
||||
private readonly ConcurrentDictionary<string, PendingApprovalRequest> _pendingApprovals = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> _requestApprovedTools = new(StringComparer.Ordinal);
|
||||
@@ -54,11 +55,40 @@ internal sealed class CopilotApprovalCoordinator
|
||||
IReadOnlyDictionary<string, string> toolNamesByCallId,
|
||||
Func<ApprovalRequestedEventDto, Task> onApproval,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return await RequestApprovalAsync(
|
||||
command,
|
||||
agent,
|
||||
request,
|
||||
invocation,
|
||||
toolNamesByCallId,
|
||||
onActivity: null,
|
||||
onApproval,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<PermissionRequestResult> RequestApprovalAsync(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto agent,
|
||||
PermissionRequest request,
|
||||
PermissionInvocation invocation,
|
||||
IReadOnlyDictionary<string, string> toolNamesByCallId,
|
||||
Func<AgentActivityEventDto, Task>? onActivity,
|
||||
Func<ApprovalRequestedEventDto, Task> onApproval,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
string? toolName = ResolveApprovalToolName(request, toolNamesByCallId);
|
||||
string? autoApprovedToolName = ResolveAutoApprovedToolName(request);
|
||||
string? mcpServerApprovalKey = ResolveMcpServerApprovalKey(request);
|
||||
string? approvalCacheKey = ResolveApprovalCacheKey(toolName, autoApprovedToolName);
|
||||
|
||||
AgentActivityEventDto? fileChangeActivity = BuildToolCallFileChangeActivity(command, agent, request, toolName);
|
||||
if (fileChangeActivity is not null && onActivity is not null)
|
||||
{
|
||||
await onActivity(fileChangeActivity).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (IsToolApprovedForRequest(command.RequestId, approvalCacheKey)
|
||||
|| !RequiresToolCallApproval(command.Pattern.ApprovalPolicy, agent.Id, toolName, autoApprovedToolName, mcpServerApprovalKey))
|
||||
{
|
||||
@@ -154,6 +184,46 @@ internal sealed class CopilotApprovalCoordinator
|
||||
};
|
||||
}
|
||||
|
||||
internal static AgentActivityEventDto? BuildToolCallFileChangeActivity(
|
||||
RunTurnCommandDto command,
|
||||
PatternAgentDefinitionDto agent,
|
||||
PermissionRequest request,
|
||||
string? toolName)
|
||||
{
|
||||
if (request is not PermissionRequestWrite write)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
string? filePath = NormalizeOptionalString(write.FileName);
|
||||
if (filePath is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
string agentName = string.IsNullOrWhiteSpace(agent.Name) ? agent.Id : agent.Name;
|
||||
return new AgentActivityEventDto
|
||||
{
|
||||
Type = "agent-activity",
|
||||
RequestId = command.RequestId,
|
||||
SessionId = command.SessionId,
|
||||
ActivityType = ToolCallingActivityType,
|
||||
AgentId = NormalizeOptionalString(agent.Id),
|
||||
AgentName = NormalizeOptionalString(agentName),
|
||||
ToolName = NormalizeOptionalString(toolName),
|
||||
ToolCallId = NormalizeOptionalString(write.ToolCallId),
|
||||
FileChanges =
|
||||
[
|
||||
new ToolCallFileChangeDto
|
||||
{
|
||||
Path = filePath,
|
||||
Diff = NormalizeOptionalPreviewText(write.Diff),
|
||||
NewFileContents = NormalizeOptionalPreviewText(write.NewFileContents),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
internal static PermissionDetailDto BuildPermissionDetail(PermissionRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
@@ -495,6 +565,11 @@ internal sealed class CopilotApprovalCoordinator
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
|
||||
private static string? NormalizeOptionalPreviewText(string? value)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string>? NormalizeOptionalStringList(IEnumerable<string?> values)
|
||||
{
|
||||
List<string> normalized = values
|
||||
|
||||
@@ -50,6 +50,7 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
|
||||
request,
|
||||
invocation,
|
||||
state.ToolNamesByCallId,
|
||||
activity => EmitActivityAsync(command, state, activity, onEvent),
|
||||
onApproval,
|
||||
runCancellation.Token),
|
||||
(agent, request, invocation) => _userInputCoordinator.RequestUserInputAsync(
|
||||
|
||||
@@ -74,6 +74,7 @@ internal static class WorkflowRequestInfoInterpreter
|
||||
AgentId = activeAgent.AgentId,
|
||||
AgentName = activeAgent.AgentName,
|
||||
ToolName = tool.ToolName,
|
||||
ToolCallId = tool.ToolCallId,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1368,6 +1368,70 @@ public sealed class CopilotWorkflowRunnerTests
|
||||
Assert.Equal(PermissionRequestResultKind.Approved, result.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestApprovalAsync_EmitsFileChangeActivityForWriteRequests()
|
||||
{
|
||||
CopilotApprovalCoordinator coordinator = new();
|
||||
AgentActivityEventDto? observedActivity = null;
|
||||
ApprovalRequestedEventDto? observedApproval = null;
|
||||
RunTurnCommandDto command = CreateApprovalCommand();
|
||||
|
||||
Task<PermissionRequestResult> pending = coordinator.RequestApprovalAsync(
|
||||
command,
|
||||
command.Pattern.Agents[0],
|
||||
new PermissionRequestWrite
|
||||
{
|
||||
Kind = "write",
|
||||
ToolCallId = "tool-call-write-1",
|
||||
Intention = "Update the README",
|
||||
FileName = "README.md",
|
||||
Diff = "@@ -1 +1 @@",
|
||||
NewFileContents = "# Aryx\n",
|
||||
},
|
||||
new PermissionInvocation
|
||||
{
|
||||
SessionId = "copilot-session-1",
|
||||
},
|
||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["tool-call-write-1"] = "apply_patch",
|
||||
},
|
||||
activity =>
|
||||
{
|
||||
observedActivity = activity;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
approval =>
|
||||
{
|
||||
observedApproval = approval;
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.False(pending.IsCompleted);
|
||||
Assert.NotNull(observedActivity);
|
||||
Assert.NotNull(observedApproval);
|
||||
Assert.Equal("tool-calling", observedActivity!.ActivityType);
|
||||
Assert.Equal("apply_patch", observedActivity.ToolName);
|
||||
Assert.Equal("tool-call-write-1", observedActivity.ToolCallId);
|
||||
|
||||
ToolCallFileChangeDto preview = Assert.Single(observedActivity.FileChanges!);
|
||||
Assert.Equal("README.md", preview.Path);
|
||||
Assert.Equal("@@ -1 +1 @@", preview.Diff);
|
||||
Assert.Equal("# Aryx\n", preview.NewFileContents);
|
||||
|
||||
await coordinator.ResolveApprovalAsync(
|
||||
new ResolveApprovalCommandDto
|
||||
{
|
||||
ApprovalId = observedApproval!.ApprovalId,
|
||||
Decision = "approved",
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
PermissionRequestResult result = await pending;
|
||||
Assert.Equal(PermissionRequestResultKind.Approved, result.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestApprovalAsync_AutoApprovesToolsThatDoNotRequireApproval()
|
||||
{
|
||||
|
||||
@@ -1735,6 +1735,8 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
|
||||
sourceAgentId: event.sourceAgentId,
|
||||
sourceAgentName: event.sourceAgentName,
|
||||
toolName: event.toolName,
|
||||
toolCallId: event.toolCallId,
|
||||
fileChanges: event.fileChanges,
|
||||
}));
|
||||
}
|
||||
if (nextRun) {
|
||||
@@ -1753,6 +1755,8 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
|
||||
sourceAgentId: event.sourceAgentId,
|
||||
sourceAgentName: event.sourceAgentName,
|
||||
toolName: event.toolName,
|
||||
toolCallId: event.toolCallId,
|
||||
fileChanges: event.fileChanges,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from '@renderer/lib/runTimelineFormatting';
|
||||
import type { OrchestrationMode } from '@shared/domain/pattern';
|
||||
import type { RunTimelineEventRecord, SessionRunRecord } from '@shared/domain/runTimeline';
|
||||
import { FileChangePreview } from '@renderer/components/chat/FileChangePreview';
|
||||
|
||||
/* ── Mode accent colours (shared with ActivityPanel) ───────── */
|
||||
|
||||
@@ -91,67 +92,76 @@ function TimelineEventRow({
|
||||
const terminal = isTerminalEvent(event.kind);
|
||||
|
||||
return (
|
||||
<button
|
||||
className={`group relative flex w-full gap-2.5 text-left transition-all duration-200 ${terminal ? 'py-1' : 'py-1.5'} ${isClickable ? 'cursor-pointer' : 'cursor-default'}`}
|
||||
disabled={!isClickable}
|
||||
onClick={isClickable ? () => onJumpToMessage(event.messageId!) : undefined}
|
||||
type="button"
|
||||
>
|
||||
<div className="relative">
|
||||
{/* Vertical connector line */}
|
||||
{!isLast && (
|
||||
<div className="absolute left-[7px] top-[22px] bottom-0 w-px bg-[var(--color-border)]" />
|
||||
)}
|
||||
|
||||
{/* Node */}
|
||||
<div className="relative z-10 flex shrink-0 items-start pt-0.5">
|
||||
<div className={`flex size-[15px] items-center justify-center rounded-full ${event.status === 'running' ? 'brand-gradient-bg' : 'bg-[var(--color-surface-2)]'}`}>
|
||||
<EventIcon kind={event.kind} status={event.status} />
|
||||
<button
|
||||
className={`group flex w-full gap-2.5 text-left transition-all duration-200 ${terminal ? 'py-1' : 'py-1.5'} ${isClickable ? 'cursor-pointer' : 'cursor-default'}`}
|
||||
disabled={!isClickable}
|
||||
onClick={isClickable ? () => onJumpToMessage(event.messageId!) : undefined}
|
||||
type="button"
|
||||
>
|
||||
{/* Node */}
|
||||
<div className="relative z-10 flex shrink-0 items-start pt-0.5">
|
||||
<div className={`flex size-[15px] items-center justify-center rounded-full ${event.status === 'running' ? 'brand-gradient-bg' : 'bg-[var(--color-surface-2)]'}`}>
|
||||
<EventIcon kind={event.kind} status={event.status} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className={`text-[11px] font-medium ${terminal ? 'text-[var(--color-text-muted)]' : 'text-[var(--color-text-secondary)]'} ${isClickable ? 'group-hover:text-[var(--color-text-accent)]' : ''}`}>
|
||||
{label}
|
||||
</span>
|
||||
{/* Approval kind badge */}
|
||||
{event.kind === 'approval' && event.approvalKind && (
|
||||
<span className={`rounded-full px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider ${
|
||||
event.status === 'running'
|
||||
? 'bg-[var(--color-status-warning)]/15 text-[var(--color-status-warning)]'
|
||||
: event.status === 'completed'
|
||||
? 'bg-[var(--color-status-success)]/15 text-[var(--color-status-success)]'
|
||||
: 'bg-[var(--color-status-error)]/15 text-[var(--color-status-error)]'
|
||||
}`}>
|
||||
{event.approvalKind === 'final-response' ? 'response' : 'tool'}
|
||||
{/* Content */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className={`text-[11px] font-medium ${terminal ? 'text-[var(--color-text-muted)]' : 'text-[var(--color-text-secondary)]'} ${isClickable ? 'group-hover:text-[var(--color-text-accent)]' : ''}`}>
|
||||
{label}
|
||||
</span>
|
||||
{/* Approval kind badge */}
|
||||
{event.kind === 'approval' && event.approvalKind && (
|
||||
<span className={`rounded-full px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider ${
|
||||
event.status === 'running'
|
||||
? 'bg-[var(--color-status-warning)]/15 text-[var(--color-status-warning)]'
|
||||
: event.status === 'completed'
|
||||
? 'bg-[var(--color-status-success)]/15 text-[var(--color-status-success)]'
|
||||
: 'bg-[var(--color-status-error)]/15 text-[var(--color-status-error)]'
|
||||
}`}>
|
||||
{event.approvalKind === 'final-response' ? 'response' : 'tool'}
|
||||
</span>
|
||||
)}
|
||||
<span className="font-mono ml-auto shrink-0 text-[9px] tabular-nums text-[var(--color-text-muted)]">{timestamp}</span>
|
||||
</div>
|
||||
|
||||
{/* Content preview for message events */}
|
||||
{preview && (
|
||||
<p className={`mt-0.5 text-[10px] leading-snug text-[var(--color-text-muted)] ${isClickable ? 'group-hover:text-[var(--color-text-secondary)]' : ''}`}>
|
||||
{preview}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Approval detail */}
|
||||
{event.kind === 'approval' && event.approvalDetail && (
|
||||
<p className="mt-0.5 text-[10px] leading-snug text-[var(--color-text-muted)]">
|
||||
{truncateContent(event.approvalDetail, 120)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Error detail */}
|
||||
{event.error && (
|
||||
<p className="mt-0.5 text-[10px] leading-snug text-[var(--color-status-error)]/80">
|
||||
{truncateContent(event.error, 120)}
|
||||
</p>
|
||||
)}
|
||||
<span className="font-mono ml-auto shrink-0 text-[9px] tabular-nums text-[var(--color-text-muted)]">{timestamp}</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Content preview for message events */}
|
||||
{preview && (
|
||||
<p className={`mt-0.5 text-[10px] leading-snug text-[var(--color-text-muted)] ${isClickable ? 'group-hover:text-[var(--color-text-secondary)]' : ''}`}>
|
||||
{preview}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Approval detail */}
|
||||
{event.kind === 'approval' && event.approvalDetail && (
|
||||
<p className="mt-0.5 text-[10px] leading-snug text-[var(--color-text-muted)]">
|
||||
{truncateContent(event.approvalDetail, 120)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Error detail */}
|
||||
{event.error && (
|
||||
<p className="mt-0.5 text-[10px] leading-snug text-[var(--color-status-error)]/80">
|
||||
{truncateContent(event.error, 120)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
{/* File change preview for tool-call events */}
|
||||
{event.kind === 'tool-call' && event.fileChanges && event.fileChanges.length > 0 && (
|
||||
<div className="relative z-10 ml-[25px] pb-1">
|
||||
<FileChangePreview fileChanges={event.fileChanges} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import { ChevronRight, FileCode2, FilePlus2 } from 'lucide-react';
|
||||
|
||||
import type { ToolCallFileChangePreview } from '@shared/contracts/sidecar';
|
||||
|
||||
/* ── Diff stat helpers ─────────────────────────────────────── */
|
||||
|
||||
interface DiffStats {
|
||||
additions: number;
|
||||
deletions: number;
|
||||
}
|
||||
|
||||
function parseDiffStats(diff: string | undefined): DiffStats {
|
||||
if (!diff) return { additions: 0, deletions: 0 };
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
for (const line of diff.split('\n')) {
|
||||
if (line.startsWith('+') && !line.startsWith('+++')) additions++;
|
||||
else if (line.startsWith('-') && !line.startsWith('---')) deletions++;
|
||||
}
|
||||
return { additions, deletions };
|
||||
}
|
||||
|
||||
function fileBaseName(path: string): string {
|
||||
const normalized = path.replace(/\\/g, '/');
|
||||
const lastSlash = normalized.lastIndexOf('/');
|
||||
return lastSlash >= 0 ? normalized.slice(lastSlash + 1) : normalized;
|
||||
}
|
||||
|
||||
function fileDir(path: string): string {
|
||||
const normalized = path.replace(/\\/g, '/');
|
||||
const lastSlash = normalized.lastIndexOf('/');
|
||||
return lastSlash > 0 ? normalized.slice(0, lastSlash + 1) : '';
|
||||
}
|
||||
|
||||
/* ── Mini diff-stats bar (GitHub-style) ────────────────────── */
|
||||
|
||||
function DiffStatsBar({ additions, deletions }: DiffStats) {
|
||||
const total = additions + deletions;
|
||||
if (total === 0) return null;
|
||||
const blocks = 5;
|
||||
const addBlocks = Math.max(additions > 0 ? 1 : 0, Math.round((additions / total) * blocks));
|
||||
const delBlocks = blocks - addBlocks;
|
||||
|
||||
return (
|
||||
<span className="inline-flex gap-px" aria-label={`${additions} additions, ${deletions} deletions`}>
|
||||
{Array.from({ length: addBlocks }, (_, i) => (
|
||||
<span key={`a${i}`} className="size-1.5 rounded-[1px] bg-[var(--color-status-success)]" />
|
||||
))}
|
||||
{Array.from({ length: delBlocks }, (_, i) => (
|
||||
<span key={`d${i}`} className="size-1.5 rounded-[1px] bg-[var(--color-status-error)]" />
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Diff line renderer ────────────────────────────────────── */
|
||||
|
||||
function DiffLine({ line }: { line: string }) {
|
||||
let textClass = 'text-[var(--color-text-secondary)]';
|
||||
let bgClass = '';
|
||||
|
||||
if (line.startsWith('+') && !line.startsWith('+++')) {
|
||||
textClass = 'text-[var(--color-status-success)]';
|
||||
bgClass = 'bg-[var(--color-status-success)]/[0.06]';
|
||||
} else if (line.startsWith('-') && !line.startsWith('---')) {
|
||||
textClass = 'text-[var(--color-status-error)]';
|
||||
bgClass = 'bg-[var(--color-status-error)]/[0.06]';
|
||||
} else if (line.startsWith('@@')) {
|
||||
textClass = 'text-[var(--color-accent-sky)]';
|
||||
} else if (line.startsWith('diff ') || line.startsWith('index ') || line.startsWith('---') || line.startsWith('+++')) {
|
||||
textClass = 'text-[var(--color-text-muted)]';
|
||||
}
|
||||
|
||||
return <div className={`${textClass} ${bgClass} -mx-3 px-3`}>{line || '\u00A0'}</div>;
|
||||
}
|
||||
|
||||
/* ── Individual file entry ─────────────────────────────────── */
|
||||
|
||||
function FileChangeEntry({ file }: { file: ToolCallFileChangePreview }) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const isNewFile = !file.diff && !!file.newFileContents;
|
||||
const stats = useMemo(() => parseDiffStats(file.diff), [file.diff]);
|
||||
const hasContent = !!file.diff || !!file.newFileContents;
|
||||
const dir = fileDir(file.path);
|
||||
const base = fileBaseName(file.path);
|
||||
|
||||
return (
|
||||
<div className="border-b border-[var(--color-border-subtle)] last:border-b-0">
|
||||
<button
|
||||
className="flex w-full items-center gap-1.5 px-2 py-[5px] text-left text-[10px] transition-colors duration-150 hover:bg-[var(--color-surface-3)]/40 disabled:cursor-default"
|
||||
disabled={!hasContent}
|
||||
onClick={hasContent ? () => setExpanded(!expanded) : undefined}
|
||||
type="button"
|
||||
aria-expanded={hasContent ? expanded : undefined}
|
||||
>
|
||||
{hasContent ? (
|
||||
<ChevronRight
|
||||
className={`size-2.5 shrink-0 text-[var(--color-text-muted)] transition-transform duration-150 ${expanded ? 'rotate-90' : ''}`}
|
||||
/>
|
||||
) : (
|
||||
<span className="w-2.5 shrink-0" />
|
||||
)}
|
||||
|
||||
{isNewFile
|
||||
? <FilePlus2 className="size-3 shrink-0 text-[var(--color-status-success)]" />
|
||||
: <FileCode2 className="size-3 shrink-0 text-[var(--color-accent-sky)]" />}
|
||||
|
||||
<span className="min-w-0 flex-1 truncate font-mono">
|
||||
{dir && <span className="text-[var(--color-text-muted)]">{dir}</span>}
|
||||
<span className="text-[var(--color-text-primary)]">{base}</span>
|
||||
</span>
|
||||
|
||||
{isNewFile ? (
|
||||
<span className="shrink-0 rounded px-1 py-px text-[8px] font-semibold uppercase tracking-wider bg-[var(--color-status-success)]/10 text-[var(--color-status-success)]">
|
||||
new
|
||||
</span>
|
||||
) : (stats.additions > 0 || stats.deletions > 0) ? (
|
||||
<span className="flex items-center gap-1.5 shrink-0">
|
||||
<span className="flex items-center gap-0.5 font-mono">
|
||||
{stats.additions > 0 && <span className="text-[var(--color-status-success)]">+{stats.additions}</span>}
|
||||
{stats.deletions > 0 && <span className="text-[var(--color-status-error)]">−{stats.deletions}</span>}
|
||||
</span>
|
||||
<DiffStatsBar additions={stats.additions} deletions={stats.deletions} />
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
|
||||
{expanded && (
|
||||
<div className="border-t border-[var(--color-border-subtle)]">
|
||||
<pre className="max-h-64 overflow-auto bg-[var(--color-surface-0)] px-3 py-1.5 font-mono text-[10px] leading-relaxed">
|
||||
{file.diff
|
||||
? file.diff.split('\n').map((line, i) => <DiffLine key={i} line={line} />)
|
||||
: file.newFileContents!.split('\n').map((line, i) => (
|
||||
<div key={i} className="text-[var(--color-text-secondary)]">{line || '\u00A0'}</div>
|
||||
))}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Main export ───────────────────────────────────────────── */
|
||||
|
||||
interface FileChangePreviewProps {
|
||||
fileChanges: ToolCallFileChangePreview[];
|
||||
}
|
||||
|
||||
export function FileChangePreview({ fileChanges }: FileChangePreviewProps) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const totalStats = useMemo(() => {
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
let newFiles = 0;
|
||||
for (const fc of fileChanges) {
|
||||
if (!fc.diff && fc.newFileContents) {
|
||||
newFiles++;
|
||||
} else {
|
||||
const s = parseDiffStats(fc.diff);
|
||||
additions += s.additions;
|
||||
deletions += s.deletions;
|
||||
}
|
||||
}
|
||||
return { additions, deletions, newFiles };
|
||||
}, [fileChanges]);
|
||||
|
||||
const fileWord = fileChanges.length === 1 ? 'file' : 'files';
|
||||
|
||||
return (
|
||||
<div className="mt-1 overflow-hidden rounded-md border border-[var(--color-border-subtle)] bg-[var(--color-surface-1)]/60">
|
||||
<button
|
||||
className="flex w-full items-center gap-1.5 px-2 py-1 text-left text-[10px] font-medium text-[var(--color-text-muted)] transition-colors duration-150 hover:bg-[var(--color-surface-2)]/40 hover:text-[var(--color-text-secondary)]"
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
aria-label={`${fileChanges.length} file changes`}
|
||||
>
|
||||
<ChevronRight
|
||||
className={`size-2.5 shrink-0 transition-transform duration-150 ${expanded ? 'rotate-90' : ''}`}
|
||||
/>
|
||||
<span>{fileChanges.length} {fileWord} changed</span>
|
||||
|
||||
{(totalStats.additions > 0 || totalStats.deletions > 0) && (
|
||||
<span className="ml-auto flex shrink-0 items-center gap-1.5 font-mono">
|
||||
{totalStats.additions > 0 && (
|
||||
<span className="text-[var(--color-status-success)]">+{totalStats.additions}</span>
|
||||
)}
|
||||
{totalStats.deletions > 0 && (
|
||||
<span className="text-[var(--color-status-error)]">−{totalStats.deletions}</span>
|
||||
)}
|
||||
<DiffStatsBar additions={totalStats.additions} deletions={totalStats.deletions} />
|
||||
</span>
|
||||
)}
|
||||
{totalStats.newFiles > 0 && (
|
||||
<span className={`shrink-0 rounded px-1 py-px text-[8px] font-semibold uppercase tracking-wider bg-[var(--color-status-success)]/10 text-[var(--color-status-success)] ${totalStats.additions === 0 && totalStats.deletions === 0 ? 'ml-auto' : ''}`}>
|
||||
{totalStats.newFiles} new
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{expanded && (
|
||||
<div className="border-t border-[var(--color-border-subtle)]">
|
||||
{fileChanges.map((fc) => (
|
||||
<FileChangeEntry file={fc} key={fc.path} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -241,6 +241,12 @@ export interface TurnCompleteEvent {
|
||||
|
||||
export type AgentActivityType = 'thinking' | 'tool-calling' | 'handoff' | 'completed';
|
||||
|
||||
export interface ToolCallFileChangePreview {
|
||||
path: string;
|
||||
diff?: string;
|
||||
newFileContents?: string;
|
||||
}
|
||||
|
||||
export interface AgentActivityEvent {
|
||||
type: 'agent-activity';
|
||||
requestId: string;
|
||||
@@ -251,6 +257,8 @@ export interface AgentActivityEvent {
|
||||
sourceAgentId?: string;
|
||||
sourceAgentName?: string;
|
||||
toolName?: string;
|
||||
toolCallId?: string;
|
||||
fileChanges?: ToolCallFileChangePreview[];
|
||||
}
|
||||
|
||||
export type SubagentEventKind = 'started' | 'completed' | 'failed' | 'selected' | 'deselected';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { SessionRunRecord } from '@shared/domain/runTimeline';
|
||||
|
||||
import type { QuotaSnapshot } from '@shared/contracts/sidecar';
|
||||
import type { QuotaSnapshot, ToolCallFileChangePreview } from '@shared/contracts/sidecar';
|
||||
|
||||
export type SessionActivityType = 'thinking' | 'tool-calling' | 'handoff' | 'completed';
|
||||
|
||||
@@ -36,6 +36,8 @@ export interface SessionEventRecord {
|
||||
sourceAgentId?: string;
|
||||
sourceAgentName?: string;
|
||||
toolName?: string;
|
||||
toolCallId?: string;
|
||||
fileChanges?: ToolCallFileChangePreview[];
|
||||
run?: SessionRunRecord;
|
||||
error?: string;
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
ApprovalDecision,
|
||||
PendingApprovalRecord,
|
||||
} from '@shared/domain/approval';
|
||||
import type { ToolCallFileChangePreview } from '@shared/contracts/sidecar';
|
||||
import type { PatternDefinition, ReasoningEffort } from '@shared/domain/pattern';
|
||||
import type { ProjectRecord } from '@shared/domain/project';
|
||||
import { createId } from '@shared/utils/ids';
|
||||
@@ -41,6 +42,8 @@ export interface RunTimelineEventRecord {
|
||||
targetAgentId?: string;
|
||||
targetAgentName?: string;
|
||||
toolName?: string;
|
||||
toolCallId?: string;
|
||||
fileChanges?: ToolCallFileChangePreview[];
|
||||
approvalId?: string;
|
||||
approvalKind?: ApprovalCheckpointKind;
|
||||
approvalTitle?: string;
|
||||
@@ -86,6 +89,8 @@ export interface AppendRunActivityEventInput {
|
||||
sourceAgentId?: string;
|
||||
sourceAgentName?: string;
|
||||
toolName?: string;
|
||||
toolCallId?: string;
|
||||
fileChanges?: ToolCallFileChangePreview[];
|
||||
}
|
||||
|
||||
export interface UpsertRunMessageEventInput {
|
||||
@@ -113,6 +118,87 @@ function normalizeOptionalString(value: string | undefined): string | undefined
|
||||
return trimmed ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizeOptionalPreviewText(value: string | undefined): string | undefined {
|
||||
return value?.trim() ? value : undefined;
|
||||
}
|
||||
|
||||
function normalizeToolCallFileChange(
|
||||
change: ToolCallFileChangePreview,
|
||||
): ToolCallFileChangePreview | undefined {
|
||||
const path = normalizeOptionalString(change.path);
|
||||
if (!path) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const diff = normalizeOptionalPreviewText(change.diff);
|
||||
const newFileContents = normalizeOptionalPreviewText(change.newFileContents);
|
||||
return {
|
||||
path,
|
||||
diff,
|
||||
newFileContents,
|
||||
};
|
||||
}
|
||||
|
||||
function mergeToolCallFileChange(
|
||||
existing: ToolCallFileChangePreview,
|
||||
incoming: ToolCallFileChangePreview,
|
||||
): ToolCallFileChangePreview {
|
||||
return {
|
||||
path: incoming.path,
|
||||
diff: incoming.diff ?? existing.diff,
|
||||
newFileContents: incoming.newFileContents ?? existing.newFileContents,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeToolCallFileChanges(
|
||||
changes: readonly ToolCallFileChangePreview[] | undefined,
|
||||
): ToolCallFileChangePreview[] | undefined {
|
||||
if (!changes || changes.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const normalized = new Map<string, ToolCallFileChangePreview>();
|
||||
for (const change of changes) {
|
||||
const nextChange = normalizeToolCallFileChange(change);
|
||||
if (!nextChange) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const previous = normalized.get(nextChange.path);
|
||||
normalized.set(
|
||||
nextChange.path,
|
||||
previous ? mergeToolCallFileChange(previous, nextChange) : nextChange,
|
||||
);
|
||||
}
|
||||
|
||||
return normalized.size > 0 ? [...normalized.values()] : undefined;
|
||||
}
|
||||
|
||||
function mergeToolCallFileChanges(
|
||||
existing: readonly ToolCallFileChangePreview[] | undefined,
|
||||
incoming: readonly ToolCallFileChangePreview[] | undefined,
|
||||
): ToolCallFileChangePreview[] | undefined {
|
||||
const normalizedExisting = normalizeToolCallFileChanges(existing);
|
||||
const normalizedIncoming = normalizeToolCallFileChanges(incoming);
|
||||
if (!normalizedExisting) {
|
||||
return normalizedIncoming;
|
||||
}
|
||||
|
||||
if (!normalizedIncoming) {
|
||||
return normalizedExisting;
|
||||
}
|
||||
|
||||
const merged = new Map(
|
||||
normalizedExisting.map((change) => [change.path, change] satisfies [string, ToolCallFileChangePreview]),
|
||||
);
|
||||
for (const change of normalizedIncoming) {
|
||||
const previous = merged.get(change.path);
|
||||
merged.set(change.path, previous ? mergeToolCallFileChange(previous, change) : change);
|
||||
}
|
||||
|
||||
return [...merged.values()];
|
||||
}
|
||||
|
||||
function normalizeRunTimelineAgent(
|
||||
agent: RunTimelineAgentRecord,
|
||||
): RunTimelineAgentRecord | undefined {
|
||||
@@ -153,6 +239,8 @@ function normalizeRunTimelineEvent(
|
||||
targetAgentId: normalizeOptionalString(event.targetAgentId),
|
||||
targetAgentName: normalizeOptionalString(event.targetAgentName),
|
||||
toolName: normalizeOptionalString(event.toolName),
|
||||
toolCallId: normalizeOptionalString(event.toolCallId),
|
||||
fileChanges: normalizeToolCallFileChanges(event.fileChanges),
|
||||
approvalId: normalizeOptionalString(event.approvalId),
|
||||
approvalKind: event.approvalKind,
|
||||
approvalTitle: normalizeOptionalString(event.approvalTitle),
|
||||
@@ -217,6 +305,28 @@ function appendRunTimelineEvent(
|
||||
};
|
||||
}
|
||||
|
||||
function upsertRunTimelineEventAt(
|
||||
run: SessionRunRecord,
|
||||
eventIndex: number,
|
||||
event: RunTimelineEventRecord,
|
||||
): SessionRunRecord {
|
||||
if (eventIndex < 0 || eventIndex >= run.events.length) {
|
||||
return appendRunTimelineEvent(run, event);
|
||||
}
|
||||
|
||||
const nextEvent = normalizeRunTimelineEvent(event);
|
||||
if (!nextEvent) {
|
||||
return run;
|
||||
}
|
||||
|
||||
const nextEvents = run.events.slice();
|
||||
nextEvents[eventIndex] = nextEvent;
|
||||
return {
|
||||
...run,
|
||||
events: nextEvents,
|
||||
};
|
||||
}
|
||||
|
||||
function settleOpenMessageEvents(
|
||||
run: SessionRunRecord,
|
||||
status: Extract<RunTimelineEventStatus, 'completed' | 'error'>,
|
||||
@@ -417,13 +527,26 @@ export function appendRunActivityEvent(
|
||||
}
|
||||
case 'tool-calling': {
|
||||
const agent = resolveRunTimelineAgent(run, input.agentId, input.agentName);
|
||||
return appendRunTimelineEvent(run, {
|
||||
const toolCallId = normalizeOptionalString(input.toolCallId);
|
||||
const existingIndex = toolCallId
|
||||
? run.events.findIndex((event) => event.kind === 'tool-call' && event.toolCallId === toolCallId)
|
||||
: -1;
|
||||
const existingEvent = existingIndex >= 0 ? run.events[existingIndex] : undefined;
|
||||
const nextEvent: RunTimelineEventRecord = {
|
||||
id: existingEvent?.id ?? createId('run-event'),
|
||||
kind: 'tool-call',
|
||||
occurredAt: input.occurredAt,
|
||||
occurredAt: existingEvent?.occurredAt ?? input.occurredAt,
|
||||
updatedAt: existingEvent ? input.occurredAt : undefined,
|
||||
status: 'completed',
|
||||
...agent,
|
||||
toolName: normalizeOptionalString(input.toolName),
|
||||
});
|
||||
agentId: agent.agentId ?? existingEvent?.agentId,
|
||||
agentName: agent.agentName ?? existingEvent?.agentName,
|
||||
toolName: normalizeOptionalString(input.toolName) ?? existingEvent?.toolName,
|
||||
toolCallId,
|
||||
fileChanges: mergeToolCallFileChanges(existingEvent?.fileChanges, input.fileChanges),
|
||||
};
|
||||
return existingIndex >= 0
|
||||
? upsertRunTimelineEventAt(run, existingIndex, nextEvent)
|
||||
: appendRunTimelineEvent(run, nextEvent);
|
||||
}
|
||||
case 'handoff': {
|
||||
const sourceAgent = resolveRunTimelineAgent(run, input.sourceAgentId, input.sourceAgentName);
|
||||
|
||||
@@ -167,6 +167,57 @@ describe('run timeline helpers', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('merges file change previews into a single tool-call event by toolCallId', () => {
|
||||
const baseRun = createSessionRunRecord({
|
||||
requestId: 'turn-1',
|
||||
project: createProject(),
|
||||
workspaceKind: 'project',
|
||||
pattern: createPattern(),
|
||||
triggerMessageId: 'msg-user-1',
|
||||
startedAt: '2026-03-23T00:00:01.000Z',
|
||||
});
|
||||
|
||||
const startedRun = appendRunActivityEvent(baseRun, {
|
||||
activityType: 'tool-calling',
|
||||
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||
agentId: 'agent-writer',
|
||||
toolName: 'apply_patch',
|
||||
toolCallId: 'tool-call-1',
|
||||
});
|
||||
|
||||
const firstPreviewRun = appendRunActivityEvent(startedRun, {
|
||||
activityType: 'tool-calling',
|
||||
occurredAt: '2026-03-23T00:00:03.000Z',
|
||||
agentId: 'agent-writer',
|
||||
toolName: 'apply_patch',
|
||||
toolCallId: 'tool-call-1',
|
||||
fileChanges: [{ path: 'src\\alpha.ts', diff: '@@ -1 +1 @@' }],
|
||||
});
|
||||
|
||||
const mergedRun = appendRunActivityEvent(firstPreviewRun, {
|
||||
activityType: 'tool-calling',
|
||||
occurredAt: '2026-03-23T00:00:04.000Z',
|
||||
agentId: 'agent-writer',
|
||||
toolCallId: 'tool-call-1',
|
||||
fileChanges: [{ path: 'src\\beta.ts', newFileContents: 'export const beta = true;\n' }],
|
||||
});
|
||||
|
||||
const toolCallEvents = mergedRun.events.filter((event) => event.kind === 'tool-call');
|
||||
expect(toolCallEvents).toHaveLength(1);
|
||||
expect(toolCallEvents[0]).toMatchObject({
|
||||
agentId: 'agent-writer',
|
||||
agentName: 'Writer',
|
||||
toolName: 'apply_patch',
|
||||
toolCallId: 'tool-call-1',
|
||||
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||
updatedAt: '2026-03-23T00:00:04.000Z',
|
||||
});
|
||||
expect(toolCallEvents[0].fileChanges).toEqual([
|
||||
{ path: 'src\\alpha.ts', diff: '@@ -1 +1 @@' },
|
||||
{ path: 'src\\beta.ts', newFileContents: 'export const beta = true;\n' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('normalizes missing run collections to an empty array', () => {
|
||||
expect(normalizeSessionRunRecords(undefined)).toEqual([]);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user