Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions LlamaApp.LlamaCpp.Tests/LlamaManagerModelsParsingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ public async Task A_Failed_Load_Reports_Its_Exit_Code()
Assert.Equal(-1073740791, m.LoadExitCode);
}

[Fact]
public async Task An_Interrupted_Download_Is_Incomplete_Not_Runnable()
{
// After a router/app restart llama.cpp reconstructs this entry from
// unfinished-downloads.json. It has no model instance or complete file.
var parsed = await Parse(
"""{"data":[{"id":"org/repo:Q4_K_M","status":{"value":"incomplete"},"source":"cache","can_remove":true}]}""");

var model = Assert.Single(parsed!);
Assert.True(model.IsIncomplete);
Assert.False(model.IsDownloading);
Assert.False(model.IsLoading);
Assert.False(model.IsLoaded);
Assert.True(model.CanRemove);
}

[Fact]
public async Task A_Healthy_Status_Is_Not_Failed()
{
Expand Down
12 changes: 8 additions & 4 deletions LlamaApp.LlamaCpp/LlamaManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2814,7 +2814,7 @@ public sealed record ServerModel
public string Id { get; init; } = "";
/// <summary>Absolute path to the GGUF on disk, when known.</summary>
public string? Path { get; init; }
/// <summary>Load state reported by the server: <c>unloaded</c>, <c>downloading</c>, <c>loading</c>, <c>loaded</c>, or <c>sleeping</c>.</summary>
/// <summary>Load state reported by the server: <c>unloaded</c>, <c>downloading</c>, <c>incomplete</c>, <c>loading</c>, <c>loaded</c>, or <c>sleeping</c>.</summary>
public string Status { get; init; } = "";
/// <summary>True when <see cref="Status"/> is <c>loaded</c> (model resident in a child process)
/// or <c>sleeping</c> (freed after the idle timeout but still the active model — it wakes
Expand All @@ -2831,6 +2831,10 @@ public sealed record ServerModel
/// model's files; the model is id'd by its bare repo until the download completes and the
/// quant is resolved).</summary>
public bool IsDownloading => string.Equals(Status, "downloading", StringComparison.OrdinalIgnoreCase);
/// <summary>True when an interrupted download has partial files but no
/// runnable model. Posting the same id to <c>/models</c> resumes it;
/// <c>POST /models/load</c> must not be offered for this state.</summary>
public bool IsIncomplete => string.Equals(Status, "incomplete", StringComparison.OrdinalIgnoreCase);
/// <summary>True when the server reports the last load attempt as failed —
/// the model process crashed or refused the model. Distinct from
/// <see cref="Status"/> (which is <c>unloaded</c> again): without this a
Expand Down Expand Up @@ -3516,9 +3520,9 @@ internal static bool SameDownloadModel(string eventId, string wantedId)
/// builds that wait can wedge the whole router (all <c>/models</c>
/// requests stall). <c>/models/unload</c> aborts the download promptly
/// without the remove-from-cache step, and answers as soon as the state
/// flips — the transient entry then disappears from <c>/models</c> on the
/// server's next reload sweep. Note the server drops the partial bytes on
/// abort, so the next attempt re-downloads from scratch.</para>
/// flips. Current servers retain the partial bytes and list the interrupted
/// download as <c>incomplete</c>, so posting the model again resumes it;
/// <c>DELETE /models</c> is the operation that abandons those files.</para>
/// </summary>
public async Task CancelServerDownloadAsync(string modelName)
{
Expand Down
38 changes: 38 additions & 0 deletions LlamaApp.Tests/ModelItemStateMachineTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using LlamaApp.Common;
using LlamaApp.Llama;
using LlamaApp.Views;
using Xunit;

Expand Down Expand Up @@ -177,6 +178,43 @@ public void Pausing_A_Download_Swaps_The_Ring_For_The_Resume_Glyph()
Assert.True(item.CancelDownloadVisible); // abandon affordance stays
}

[Fact]
public void Restarted_Incomplete_Download_Shows_Resume_Not_Run()
{
var item = new ModelItem();
var serverModel = new LlamaManager.ServerModel
{
Id = "org/repo:Q4_K_M",
Status = "incomplete",
};

MainWindow.SeedServerState(item, serverModel);

Assert.True(item.PendingFirstDownload);
Assert.True(item.DownloadPaused);
Assert.True(item.ResumeDownloadVisible);
Assert.True(item.CancelDownloadVisible); // abandoning deletes the partial
Assert.False(item.PlayGlyphVisible); // a partial GGUF cannot be loaded
Assert.False(item.IsDownloading);
Assert.False(item.IsLoaded);
}

[Fact]
public void Restarted_Complete_Model_Remains_Runnable()
{
var item = new ModelItem();
MainWindow.SeedServerState(item, new LlamaManager.ServerModel
{
Id = "org/repo:Q4_K_M",
Status = "unloaded",
});

Assert.False(item.PendingFirstDownload);
Assert.False(item.DownloadPaused);
Assert.True(item.PlayGlyphVisible);
Assert.False(item.ResumeDownloadVisible);
}

[Fact]
public void Resume_Glyph_Hidden_When_Idle()
{
Expand Down
81 changes: 53 additions & 28 deletions Views/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ private static ModelItem BuildLocalItem(
// repo outside the catalog. Unknown names fall to the author
// avatar / the generic icon — a row's tile is never empty.
var brand = matched?.Brand ?? ModelItem.LocalBrandFromName(repo);
return new ModelItem
var item = new ModelItem
{
Name = DeriveDisplayName(repo, quant, byRepo),
RepoName = repo,
Expand All @@ -525,12 +525,26 @@ private static ModelItem BuildLocalItem(
Downloadable = false,
Brand = brand,
Logo = ModelItem.ResolveLogoOrGeneric(brand),
IsLoaded = sm.IsLoaded,
IsDownloading = sm.IsDownloading,
// The server's path is not reliably populated — resolve
// locally when it isn't (enrolled scan map / cache layouts).
FilePath = sm.Path ?? LlamaManager.Shared.FindModelFilePath(sm.Id),
};
SeedServerState(item, sm);
return item;
}

/// <summary>
/// Seeds a newly listed row from server truth. In particular, an
/// <c>incomplete</c> entry is a retained partial download after a
/// restart, not a runnable model: it starts paused with Resume and
/// Abandon available, and without a load/play glyph.
/// </summary>
internal static void SeedServerState(ModelItem item, LlamaManager.ServerModel sm)
{
item.IsLoaded = sm.IsLoaded;
item.IsDownloading = sm.IsDownloading;
item.DownloadPaused = sm.IsIncomplete;
item.PendingFirstDownload = sm.IsIncomplete;
}

/// <summary>
Expand Down Expand Up @@ -1211,8 +1225,8 @@ void Complete()
// whose load can only fail); a pause (DownloadPaused set by
// the click) lands the row on the resume glyph instead, and a
// canceled re-download of an installed model keeps its row.
// Either way the server drops the partial bytes on abort —
// the next attempt starts the download over.
// Pausing retains the partial bytes on current servers, so
// Resume can continue the same download after this unwind.
void Abort()
{
if (toastShown) { toastShown = false; Notifications.Close(toastTag); }
Expand Down Expand Up @@ -1342,10 +1356,9 @@ private void LocalModelRetryLoad_Click(object sender, RoutedEventArgs e)
/// Fired when the cancel glyph next to the download ring is tapped:
/// cancels the in-flight download. The server is asked to abort too
/// (see <see cref="LlamaManager.DownloadModelAsync"/>); the row returns
/// to the play glyph. The server drops the partial bytes when a
/// download is aborted, so the next attempt re-downloads from scratch.
/// While paused the button abandons the partial instead — the server
/// side is already stopped, so there's nothing to cancel.
/// to the play glyph. While paused the button abandons the retained
/// partial instead. A restored first download must be deleted on the
/// server, not just removed locally, or the next poll lists it again.
/// </summary>
private void LocalModelCancelDownload_Click(object sender, RoutedEventArgs e)
{
Expand All @@ -1357,15 +1370,14 @@ private void LocalModelCancelDownload_Click(object sender, RoutedEventArgs e)

if (item.DownloadPaused)
{
// Paused: the server-side download already stopped when the
// pause was requested — just abandon the partial. A first-
// time download's row disappears from the installed list
// (nothing on disk to play); an installed model's
// re-download returns the row to the play glyph.
// A restored first download has a server-side unfinished record
// and partial files. DELETE removes both; DeleteModelFromServerAsync
// also handles older servers where the interrupted entry is gone.
// An installed model's re-download keeps the complete model row.
Log.Info("cancel clicked: abandoning paused download of " + ((IModel)item).ServerModelId);
if (item.PendingFirstDownload)
{
RemovePendingDownloadRow(item);
_ = DeleteModelFromServerAsync(item);
return;
}
item.DownloadPaused = false;
Expand Down Expand Up @@ -1444,9 +1456,9 @@ private void RemovePendingDownloadRow(ModelItem item)
/// download. Pause reuses the cancel path — the cancellation unwinds
/// <see cref="DownloadAndLaunchAsync"/> and asks the server to abort —
/// but with <see cref="ModelItem.DownloadPaused"/> set first, so the
/// row lands on the resume glyph instead of the play glyph. The
/// server drops the partial bytes when the download is aborted, so
/// resuming re-downloads from scratch. No-op for externally-triggered
/// row lands on the resume glyph instead of the play glyph. Current
/// servers retain the partial bytes, so resuming continues from them.
/// No-op for externally-triggered
/// downloads (the ring's button is
/// disabled then — see <see cref="ModelItem.CanPauseDownload"/>).
/// </summary>
Expand All @@ -1468,8 +1480,8 @@ private void LocalModelPauseDownload_Click(object sender, RoutedEventArgs e)

/// <summary>
/// Fired when the resume glyph on a paused row is tapped: restarts the
/// download → load lifecycle. The pause's abort dropped the partial
/// bytes server-side, so this starts the download over.
/// download → load lifecycle. Posting the same model id resumes any
/// partial files retained on the server, including after an app restart.
/// </summary>
private void LocalModelResumeDownload_Click(object sender, RoutedEventArgs e)
{
Expand Down Expand Up @@ -2620,9 +2632,9 @@ private async Task ReconcileAsync(IReadOnlyList<LlamaManager.ServerModel> server
if (item.FilePath is null)
item.FilePath = sm.Path ?? LlamaManager.Shared.FindModelFilePath(sm.Id);

// Server truth: any state but "downloading" means the model
// exists in the cache — no longer a pending first download.
if (!sm.IsDownloading)
// Only a complete cached model is no longer a pending first
// download. An interrupted one remains pending and resumable.
if (!sm.IsDownloading && !sm.IsIncomplete)
item.PendingFirstDownload = false;

// Map the server's model states onto the row:
Expand All @@ -2634,6 +2646,7 @@ private async Task ReconcileAsync(IReadOnlyList<LlamaManager.ServerModel> server
// downloading-> download ring (server-truth download; stays
// indeterminate for externally-triggered
// downloads — no byte progress is tracked)
// incomplete -> resume glyph (retained partial, not runnable)
// unloaded -> play glyph (but don't clobber an optimistic
// IsLoading set by a just-fired play click that
// the server hasn't acknowledged yet)
Expand All @@ -2646,7 +2659,7 @@ private async Task ReconcileAsync(IReadOnlyList<LlamaManager.ServerModel> server
// a request the server never picked up. Surface it as a
// failure instead of spinning forever.
if (item.IsLoading &&
!sm.IsLoading && !sm.IsLoaded && !sm.IsDownloading &&
!sm.IsLoading && !sm.IsLoaded && !sm.IsDownloading && !sm.IsIncomplete &&
DateTime.UtcNow - item.LoadingSinceUtc > OptimisticLoadGrace)
{
Log.Warn("load did not materialize: " + sm.Id +
Expand All @@ -2671,6 +2684,7 @@ private async Task ReconcileAsync(IReadOnlyList<LlamaManager.ServerModel> server
item.IsLoaded = true;
item.IsLoading = false;
item.IsDownloading = false;
item.DownloadPaused = false;
item.LoadFailed = false; // server-truth loaded clears any stale failure
StopExternalDownloadWatch(item);
}
Expand All @@ -2693,6 +2707,17 @@ private async Task ReconcileAsync(IReadOnlyList<LlamaManager.ServerModel> server
item.IsLoaded = false;
item.IsLoading = true;
item.IsDownloading = false;
item.DownloadPaused = false;
StopExternalDownloadWatch(item);
}
else if (sm.IsIncomplete)
{
item.IsLoaded = false;
item.IsLoading = false;
item.IsDownloading = false;
item.DownloadFailed = false;
item.LoadFailed = false;
item.DownloadPaused = true;
StopExternalDownloadWatch(item);
}
else // "unloaded" (or unknown)
Expand Down Expand Up @@ -2795,13 +2820,13 @@ private async Task ReconcileAsync(IReadOnlyList<LlamaManager.ServerModel> server
// owns the poller's).
if (serverIds.Count > 0)
{
// A row's model counts as present only when it is busy
// (downloading / loading / loaded — see ModelPresence for why
// each must stay) or its file is findable on disk. The
// A row's model counts as present only when it is busy or
// resumable (downloading / incomplete / loading / loaded — see
// ModelPresence for why each must stay) or its file is findable on disk. The
// server-reported path wins when given; local resolution
// (enrolled scan map / cache layouts) is the fallback.
bool IsBusy(string id) => serverModels.Any(m =>
m.Id == id && (m.IsDownloading || m.IsLoading || m.IsLoaded));
m.Id == id && (m.IsDownloading || m.IsIncomplete || m.IsLoading || m.IsLoaded));
bool FileOnDisk(string id)
{
var sm = serverModels.FirstOrDefault(m => m.Id == id);
Expand Down
4 changes: 2 additions & 2 deletions Views/ModelItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -309,8 +309,8 @@ public CancellationTokenSource? DownloadCancellation
/// <summary>
/// True when the user paused the download by clicking the progress ring.
/// The server-side download is already aborted (pause reuses the cancel
/// path — the server drops the partial bytes on abort, so resuming
/// re-downloads from scratch), so the row swaps the ring for a resume
/// path — current servers retain the partial bytes for resume), so the
/// row swaps the ring for a resume
/// glyph in the same slot; clicking it restarts the download. Set by the
/// row's pause button before the cancellation unwinds; cleared by the
/// download driver on (re)start, completion, or failure.
Expand Down
Loading