Skip to content

Commit 556e7da

Browse files
authored
feat: add Workspace session file rail
Add a Workspace page file rail backed by sessions.files.list/get, with legacy agents.files fallback for older gateways, safe text/markdown previews, path browsing, search, metadata badges, localization, and projection tests.\n\nCo-authored-by: Copilot <[email protected]>
1 parent 7257d29 commit 556e7da

11 files changed

Lines changed: 1915 additions & 132 deletions

File tree

Lines changed: 372 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,372 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text.Json;
5+
using OpenClaw.Shared;
6+
7+
namespace OpenClawTray.Pages;
8+
9+
/// <summary>
10+
/// Pure projection layer for the Workspace page's session file rail. Adapts the
11+
/// typed gateway protocol DTOs (<see cref="SessionFileList"/> /
12+
/// <see cref="SessionFileContent"/> from <c>sessions.files.list/get</c>) into
13+
/// view rows and owns the search/sort/format logic so the code-behind stays a
14+
/// thin view.
15+
///
16+
/// This layer <i>consumes</i> the protocol DTOs — it does not re-parse wire JSON
17+
/// or redefine the protocol contract (that lives in
18+
/// <c>OpenClaw.Shared.GatewayProtocolModels</c> /
19+
/// <c>OpenClawGatewayClient.Protocol</c>).
20+
/// </summary>
21+
internal static class WorkspaceFilesModel
22+
{
23+
/// <summary>One row in the workspace file rail.</summary>
24+
internal sealed record WorkspaceFileEntry
25+
{
26+
/// <summary>Display name (leaf name, never a path).</summary>
27+
public required string Name { get; init; }
28+
29+
/// <summary>
30+
/// Normalized workspace-relative path used for grouping/search/display.
31+
/// </summary>
32+
public required string RelativePath { get; init; }
33+
34+
/// <summary>
35+
/// The original path string from the gateway DTO — used verbatim when
36+
/// requesting content via <c>sessions.files.get</c> so normalization
37+
/// never diverges from what the gateway expects.
38+
/// </summary>
39+
public required string RequestPath { get; init; }
40+
41+
/// <summary>Size in bytes; <c>null</c> when unknown.</summary>
42+
public long? Size { get; init; }
43+
44+
/// <summary>False when the file is tracked but missing on disk.</summary>
45+
public bool Exists { get; init; } = true;
46+
47+
/// <summary>True for browser/directory entries (not openable as text).</summary>
48+
public bool IsDirectory { get; init; }
49+
50+
/// <summary>True when this row came from transcript/session relevance.</summary>
51+
public bool IsSessionFile { get; init; }
52+
53+
/// <summary>True when selecting this file may call <c>sessions.files.get</c>.</summary>
54+
public bool CanPreview { get; init; }
55+
56+
/// <summary>The agent wrote/modified this file during the session.</summary>
57+
public bool Touched { get; init; }
58+
59+
/// <summary>The agent read this file during the session.</summary>
60+
public bool Read { get; init; }
61+
62+
/// <summary>Last-modified time (UTC) when the gateway reports it.</summary>
63+
public DateTimeOffset? ModifiedUtc { get; init; }
64+
}
65+
66+
/// <summary>View state derived from a <see cref="SessionFileList"/>.</summary>
67+
internal sealed record WorkspaceListState
68+
{
69+
/// <summary>Absolute workspace root, or empty when not reported.</summary>
70+
public string WorkspacePath { get; init; } = string.Empty;
71+
72+
/// <summary>
73+
/// False when the connected gateway does not implement the method
74+
/// (older gateway). Mirrors <see cref="SessionFileList.IsSupported"/>.
75+
/// </summary>
76+
public bool Supported { get; init; } = true;
77+
78+
public IReadOnlyList<WorkspaceFileEntry> Entries { get; init; } =
79+
Array.Empty<WorkspaceFileEntry>();
80+
81+
public string BrowserPath { get; init; } = string.Empty;
82+
83+
public string? BrowserParentPath { get; init; }
84+
85+
public string BrowserSearch { get; init; } = string.Empty;
86+
87+
public bool BrowserTruncated { get; init; }
88+
}
89+
90+
/// <summary>
91+
/// Project a typed <see cref="SessionFileList"/> into sorted view rows.
92+
/// Merges the transcript-referenced <see cref="SessionFileList.Files"/> with
93+
/// any optional <see cref="SessionFileList.Browser"/> entries (deduped by
94+
/// path, preferring the richer file entry).
95+
/// </summary>
96+
public static WorkspaceListState FromSessionFileList(SessionFileList list)
97+
{
98+
if (list == null) return new WorkspaceListState();
99+
100+
if (!list.IsSupported)
101+
return new WorkspaceListState { Supported = false, WorkspacePath = list.Root ?? string.Empty };
102+
103+
// Identity is case-sensitive: a gateway-backed workspace can contain
104+
// distinct paths that differ only by case.
105+
var byPath = new Dictionary<string, WorkspaceFileEntry>(StringComparer.Ordinal);
106+
var order = new List<string>();
107+
108+
void Add(WorkspaceFileEntry entry)
109+
{
110+
if (!byPath.ContainsKey(entry.RelativePath))
111+
order.Add(entry.RelativePath);
112+
byPath[entry.RelativePath] = entry;
113+
}
114+
115+
foreach (var f in list.Files ?? Array.Empty<SessionFileEntry>())
116+
{
117+
if (MapFileEntry(f) is { } entry) Add(entry);
118+
}
119+
120+
// Browser entries (present only when a path/search was requested) fill in
121+
// directory rows and any files not already referenced by the transcript.
122+
foreach (var b in list.Browser?.Entries ?? Array.Empty<SessionFileBrowserEntry>())
123+
{
124+
if (MapBrowserEntry(b) is not { } entry) continue;
125+
if (byPath.ContainsKey(entry.RelativePath)) continue; // file entry wins
126+
Add(entry);
127+
}
128+
129+
var entries = Sort(order.Select(p => byPath[p]).ToList());
130+
var browser = list.Browser;
131+
132+
return new WorkspaceListState
133+
{
134+
WorkspacePath = list.Root ?? string.Empty,
135+
Supported = true,
136+
Entries = entries,
137+
BrowserPath = NormalizeBrowserPath(browser?.Path),
138+
BrowserParentPath = browser?.ParentPath is { Length: > 0 } parent
139+
? NormalizeBrowserPath(parent)
140+
: browser?.ParentPath,
141+
BrowserSearch = browser?.Search ?? string.Empty,
142+
BrowserTruncated = browser?.Truncated ?? false,
143+
};
144+
}
145+
146+
/// <summary>
147+
/// Project the legacy <c>agents.files.list</c> payload used by older
148+
/// gateways. It does not support path browsing or session relevance badges,
149+
/// but the rows remain previewable through <c>agents.files.get</c>.
150+
/// </summary>
151+
public static WorkspaceListState FromLegacyAgentFilesList(JsonElement payload)
152+
{
153+
var entries = new List<WorkspaceFileEntry>();
154+
if (payload.ValueKind != JsonValueKind.Object)
155+
return new WorkspaceListState();
156+
157+
if (payload.TryGetProperty("files", out var filesEl) &&
158+
filesEl.ValueKind == JsonValueKind.Array)
159+
{
160+
foreach (var fileEl in filesEl.EnumerateArray())
161+
{
162+
if (MapLegacyFileEntry(fileEl) is { } entry)
163+
entries.Add(entry);
164+
}
165+
}
166+
167+
return new WorkspaceListState
168+
{
169+
WorkspacePath = GetString(payload, "workspace") ?? GetString(payload, "root") ?? string.Empty,
170+
Supported = true,
171+
Entries = Sort(entries),
172+
};
173+
}
174+
175+
private static WorkspaceFileEntry? MapFileEntry(SessionFileEntry f)
176+
{
177+
var requestPath = !string.IsNullOrEmpty(f.Path) ? f.Path : f.Name;
178+
if (string.IsNullOrEmpty(requestPath)) return null;
179+
180+
var relative = NormalizePath(requestPath);
181+
var name = !string.IsNullOrEmpty(f.Name) ? f.Name : LeafName(relative);
182+
if (string.IsNullOrEmpty(name)) return null;
183+
184+
return new WorkspaceFileEntry
185+
{
186+
Name = name,
187+
RelativePath = relative,
188+
RequestPath = requestPath,
189+
Size = f.Size is >= 0 ? f.Size : null,
190+
Exists = !f.Missing,
191+
IsDirectory = false,
192+
IsSessionFile = true,
193+
CanPreview = true,
194+
Touched = string.Equals(f.Kind, "modified", StringComparison.OrdinalIgnoreCase),
195+
Read = string.Equals(f.Kind, "read", StringComparison.OrdinalIgnoreCase),
196+
ModifiedUtc = ToUtc(f.UpdatedAt),
197+
};
198+
}
199+
200+
private static WorkspaceFileEntry? MapBrowserEntry(SessionFileBrowserEntry b)
201+
{
202+
var requestPath = !string.IsNullOrEmpty(b.Path) ? b.Path : b.Name;
203+
if (string.IsNullOrEmpty(requestPath)) return null;
204+
205+
var relative = NormalizePath(requestPath);
206+
var name = !string.IsNullOrEmpty(b.Name) ? b.Name : LeafName(relative);
207+
if (string.IsNullOrEmpty(name)) return null;
208+
209+
// SessionKind reflects relevance: "modified" / "read" / "mixed".
210+
// Compare case-insensitively for consistency with MapFileEntry.
211+
bool touched = string.Equals(b.SessionKind, "modified", StringComparison.OrdinalIgnoreCase)
212+
|| string.Equals(b.SessionKind, "mixed", StringComparison.OrdinalIgnoreCase);
213+
bool read = string.Equals(b.SessionKind, "read", StringComparison.OrdinalIgnoreCase);
214+
bool isDirectory = b.IsDirectory;
215+
bool isSessionFile = touched || read;
216+
217+
return new WorkspaceFileEntry
218+
{
219+
Name = name,
220+
RelativePath = relative,
221+
RequestPath = requestPath,
222+
Size = b.Size is >= 0 ? b.Size : null,
223+
Exists = true,
224+
IsDirectory = isDirectory,
225+
IsSessionFile = isSessionFile,
226+
CanPreview = !isDirectory && isSessionFile,
227+
Touched = touched,
228+
Read = read,
229+
ModifiedUtc = ToUtc(b.UpdatedAt),
230+
};
231+
}
232+
233+
private static WorkspaceFileEntry? MapLegacyFileEntry(JsonElement item)
234+
{
235+
if (item.ValueKind != JsonValueKind.Object) return null;
236+
237+
var requestPath = GetString(item, "path") ?? GetString(item, "name");
238+
if (string.IsNullOrEmpty(requestPath)) return null;
239+
240+
var relative = NormalizePath(requestPath);
241+
var name = GetString(item, "name") ?? LeafName(relative);
242+
if (string.IsNullOrEmpty(name)) return null;
243+
244+
return new WorkspaceFileEntry
245+
{
246+
Name = name,
247+
RelativePath = relative,
248+
RequestPath = requestPath,
249+
Size = GetLong(item, "size"),
250+
Exists = GetBool(item, "exists") ?? !GetBool(item, "missing").GetValueOrDefault(),
251+
IsDirectory = false,
252+
IsSessionFile = true,
253+
CanPreview = true,
254+
ModifiedUtc = ToUtc(GetDateTime(item, "updatedAt") ?? GetDateTime(item, "modifiedAt")),
255+
};
256+
}
257+
258+
/// <summary>
259+
/// Filter entries by a free-text query matched (case-insensitive) against
260+
/// the leaf name and the relative path. Whitespace-only queries return the
261+
/// full list unchanged. Ordering is stable (input order preserved).
262+
/// </summary>
263+
public static IReadOnlyList<WorkspaceFileEntry> Filter(
264+
IReadOnlyList<WorkspaceFileEntry> entries, string? query)
265+
{
266+
if (entries.Count == 0)
267+
return entries;
268+
269+
var trimmed = query?.Trim();
270+
if (string.IsNullOrEmpty(trimmed))
271+
return entries;
272+
273+
return entries
274+
.Where(e =>
275+
e.Name.Contains(trimmed, StringComparison.OrdinalIgnoreCase) ||
276+
e.RelativePath.Contains(trimmed, StringComparison.OrdinalIgnoreCase))
277+
.ToList();
278+
}
279+
280+
/// <summary>
281+
/// Default rail ordering: directories first, then files the agent edited,
282+
/// then files it only read, then the rest; alphabetical by relative path
283+
/// within each tier. Deterministic so the UI does not jitter between
284+
/// refreshes.
285+
/// </summary>
286+
public static IReadOnlyList<WorkspaceFileEntry> Sort(
287+
IReadOnlyList<WorkspaceFileEntry> entries)
288+
{
289+
return entries
290+
.OrderBy(Rank)
291+
.ThenBy(e => e.RelativePath, StringComparer.OrdinalIgnoreCase)
292+
.ToList();
293+
294+
static int Rank(WorkspaceFileEntry e) =>
295+
e.IsDirectory ? 0 : e.Touched ? 1 : e.Read ? 2 : 3;
296+
}
297+
298+
/// <summary>Human-readable byte size (B / KB / MB).</summary>
299+
public static string FormatSize(long? bytes)
300+
{
301+
if (bytes is not { } b || b < 0) return string.Empty;
302+
if (b < 1024) return $"{b} B";
303+
if (b < 1024 * 1024) return $"{b / 1024.0:F1} KB";
304+
return $"{b / (1024.0 * 1024.0):F1} MB";
305+
}
306+
307+
/// <summary>
308+
/// The parent folder portion of a relative path, or empty when the file
309+
/// sits at the workspace root. Used to render a subtle path caption.
310+
/// </summary>
311+
public static string DirectoryOf(string relativePath)
312+
{
313+
if (string.IsNullOrEmpty(relativePath)) return string.Empty;
314+
var idx = relativePath.LastIndexOf('/');
315+
return idx <= 0 ? string.Empty : relativePath[..idx];
316+
}
317+
318+
public static string NormalizeBrowserPath(string? path) =>
319+
string.IsNullOrWhiteSpace(path) ? string.Empty : NormalizePath(path.Trim()).TrimEnd('/');
320+
321+
private static string LeafName(string? path)
322+
{
323+
if (string.IsNullOrEmpty(path)) return string.Empty;
324+
var normalized = path.Replace('\\', '/').TrimEnd('/');
325+
var idx = normalized.LastIndexOf('/');
326+
return idx < 0 ? normalized : normalized[(idx + 1)..];
327+
}
328+
329+
private static string NormalizePath(string path) =>
330+
path.Replace('\\', '/').TrimStart('/');
331+
332+
private static DateTimeOffset? ToUtc(DateTime? value)
333+
{
334+
if (value is not { } dt) return null;
335+
return dt.Kind == DateTimeKind.Unspecified
336+
? new DateTimeOffset(DateTime.SpecifyKind(dt, DateTimeKind.Utc))
337+
: new DateTimeOffset(dt.ToUniversalTime());
338+
}
339+
340+
private static string? GetString(JsonElement item, string name)
341+
{
342+
return item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String
343+
? value.GetString()
344+
: null;
345+
}
346+
347+
private static bool? GetBool(JsonElement item, string name)
348+
{
349+
return item.TryGetProperty(name, out var value) && value.ValueKind is JsonValueKind.True or JsonValueKind.False
350+
? value.GetBoolean()
351+
: null;
352+
}
353+
354+
private static long? GetLong(JsonElement item, string name)
355+
{
356+
return item.TryGetProperty(name, out var value) &&
357+
value.ValueKind == JsonValueKind.Number &&
358+
value.TryGetInt64(out var result) &&
359+
result >= 0
360+
? result
361+
: null;
362+
}
363+
364+
private static DateTime? GetDateTime(JsonElement item, string name)
365+
{
366+
return item.TryGetProperty(name, out var value) &&
367+
value.ValueKind == JsonValueKind.String &&
368+
DateTime.TryParse(value.GetString(), null, System.Globalization.DateTimeStyles.RoundtripKind, out var result)
369+
? result
370+
: null;
371+
}
372+
}

0 commit comments

Comments
 (0)