diff --git a/app/AGENTS.md b/app/AGENTS.md
index b5fc7cc3a..7bb3b3c06 100644
--- a/app/AGENTS.md
+++ b/app/AGENTS.md
@@ -32,9 +32,11 @@ Key structure:
- **Line breaks** - Every text AI Studio builds ends its lines with LF, on every system: use `AppendLineLF` of `SharedTools.Text` instead of `StringBuilder.AppendLine`, and `'\n'` instead of `Environment.NewLine`. Both of them write CR LF on Windows, where no pipeline runs the tests; MWAIS0018 refuses them, and its code fix offers the replacement. Where a format needs CR LF, write it on purpose, as `CsvWriter.ROW_END` does. A raw string literal and a file which comes with the app keep the line endings of the checkout, CR LF on Windows with `core.autocrlf`: a test which compares such a text with what the app built normalizes it first, e.g. with `ReplaceLineEndings("\n")`.
- **Bursts in the log** - Never log one line per item of something which arrives in bursts, such as the changes a file system watcher reports, the files of a run, or the mails of a folder: a build or a sync tool changes thousands of files within seconds. Log the first item and then a summary with counts, as `FileSourceIndexer` does with `WatcherChangeTally`, or one summary per run with a few examples. Every log line of the .NET server travels to the runtime, and `RustLogForwarder` drops lines once its queue is full.
- **Message Bus** - Singleton event bus for cross-component communication inside the .NET app
+- **Loops of a component** - Blazor may dispose a component while its `OnInitializedAsync` still awaits something, and the getter `Token` of a disposed `CancellationTokenSource` throws. The exception ends the connection of the window, which then shows a page without its data until it reloads. Therefore, take the token of a source which `DisposeResources` disposes before the first `await`, as `ElapsedTime` does, and start nothing after the awaits once that token is cancelled.
- **Prompt injection reports** - The user hears once per action about what the filter removed, as soon as that action ends. Content which belongs to an action carries its scope from `PromptInjectionGuardService.BeginAction` down to where it is read or filtered; whatever is filtered without a scope is reported right away. Pass the scope as a parameter, never through a field or an `AsyncLocal`: the service serves the whole app, and the message bus delivers to other receivers in the execution context of whoever sends.
- **Paths in stored data** - A stored path to a file which AI Studio keeps below the data directory, such as a transcript or a tokenizer copy, is relative to that directory, so that a backup or a copy of the data directory works on another computer, under another user name, or on another OS. Mark such a property with `[JsonConverter(typeof(DataDirectoryRelativePathConverter))]`, for a positional record parameter with `[property: ...]`; in memory, the path stays absolute. Better still, derive the path from IDs and store none, as `VisualBriefingStore` does. Paths to files of the user stay absolute. Chats stored before v26.10.1 are migrated by a compatibility shim, see `documentation/compatibility-shims/2026-10-relative-data-paths.md`.
- **New files and folders in the data or configuration directory** - Whoever adds a file or folder directly to the data or configuration directory, or below `plugins/` or `databases/` one which needs a decision of its own, lists it in `DataBackupContents.ENTRIES`: as part of a backup, or with the reason a backup leaves it out. A backup takes along only what is listed as included, and a restore replaces only that. An entry included in a backup also goes into `REPLACEABLE_ELEMENTS` in `runtime/src/data_restore.rs`; otherwise the runtime refuses to restore it. The folder panel on the information page shows the list to users who back up these folders with a tool of their own.
+- **Temporary files** - AI Studio keeps them in `tmp/` below the data directory, through `TemporaryFiles`, never in the temporary folder of the system: on many Linux systems, that folder lives in memory, in a Flatpak always, limited to a tenth of it, and all users of a Linux computer share it. `TemporaryFiles.GetFilePath` makes up a unique path, `CreateDirectory` a folder of its own; AI Studio empties `tmp/` when it starts, before any service runs, and when it stops, so a file left there by a crash disappears with the next start. Still delete what you created once you are done, since AI Studio may run for weeks. MWAIS0019 refuses `Path.GetTempPath` and `Path.GetTempFileName`; code which needs the folder of the system all the same, such as a diagnostic which has to outlast a restart, says why next to a pragma. A folder of a former version goes into `FOLDERS_OF_EARLIER_VERSIONS`, so that the start removes it.
- **Sending content on** - Content which leaves one place for another, such as the result of an assistant sent to another assistant or a text sent into the chat, travels as a `TextLaunchPayload` through `AssistantLaunchService`, together with the restrictions of where it was written (`ChatRestrictions`, see `ChatThread.CaptureRestrictions`). Never hand over a bare string: the destination would let any provider or tool see content which its source kept from them. Build the payload with `AssistantLaunchService.CreateTextPayloadAsync`, which filters what an AI wrote for prompt injections before it reaches the next model as a message of the user. An assistant which allows sending to it overrides `AssistantBase.ApplyTextLaunchPayload`, and `SendToReceiverTests` checks that every one does; the restrictions themselves are applied centrally in `AssistantBase`.
- **JSON in model answers** - Read the JSON part of a model answer with `ModelAnswerJson`, never with a scanner of your own. It skips the prose and code fences around the JSON but checks nothing, so broken JSON reaches the deserializer unchanged and its message can go back to the model.
- **JSON contracts** - The contracts of all JSON which AI Studio reads or writes are generated while compiling. Each kind of options names the `JsonSerializerContext` which knows its types, with `GenerationMode = Metadata`, as its `TypeInfoResolver` and ends with `.AsReadOnly()`; only `VisualBriefingJson.Canonical` leaves that out, see MWAIS0010. A new JSON type goes into the context of the options it is read or written with, and into `JsonTestRoots` in `app/Tests/Serialization/`, whose contract, defaults, and coverage tests then check it. Give JSON types `set` instead of `init`, because the source generator of .NET 10 drops the initializer of an `init` property which the JSON leaves out, and write a record or a `JsonObject` instead of an anonymous type. Never call System.Text.Json without options, nor with `JsonSerializerOptions.Default`, `.Web`, or a `DefaultJsonTypeInfoResolver`: each of them builds the contracts by reflection, whose code a published build may lack. MWAIS0015 refuses them while compiling, `JsonOptionsResolverTests` checks the resolvers of all options of the app, and the trim smoke test of `dotnet run -- verify` builds the contract of every type of their contexts in a trimmed build. Reflection itself stays switched on, because Blazor Server needs it for JSON of its own, see `Trimming.props`.
diff --git a/app/Build/Flatpak/build-in-container.sh b/app/Build/Flatpak/build-in-container.sh
index ca3714616..36ab08194 100644
--- a/app/Build/Flatpak/build-in-container.sh
+++ b/app/Build/Flatpak/build-in-container.sh
@@ -110,6 +110,74 @@ echo "${yq_sha256} $BUILD_DIRECTORY/tools/yq" | sha256sum --check --strict
chmod 755 "$BUILD_DIRECTORY/tools/yq"
export PATH="$BUILD_DIRECTORY/tools:$PATH"
+# Since the image of 2026-11-29, flatpak-validate-icon loads images through glycin, which starts a loader for each
+# image in a bwrap sandbox, with a seccomp filter and a limit on its address space. Under the emulation of another CPU
+# architecture, e.g., x86_64 by Rosetta on Apple Silicon, neither works: the kernel refuses the filter, and Rosetta
+# cannot start within the limit. glycin has no fallback, so flatpak build-export refuses every icon with "Format not
+# recognized". A probe with a valid PNG tells whether the validator can load images here. When it cannot, the export
+# checks the icons with a fallback instead, which reads their format and size but does not decode them. The CI of the
+# Flatpak repository and Flathub build natively and check the icons in full.
+stage "Checking the icon validator"
+icon_validator="$(dirname "$(command -v flatpak)")/../libexec/flatpak-validate-icon"
+[ -x "$icon_validator" ] || fail "the image lacks flatpak-validate-icon next to flatpak"
+
+python3 -I - "$BUILD_DIRECTORY/tools/probe.png" <<'EOF'
+import struct
+import sys
+import zlib
+
+def chunk(kind, data):
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
+
+rows = b"".join(b"\x00" + b"\x00\x00\x00\xff" * 16 for _ in range(16))
+with open(sys.argv[1], "wb") as png:
+ png.write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 16, 16, 8, 6, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b""))
+EOF
+
+icon_check="full"
+if "$icon_validator" --sandbox 512 512 "$BUILD_DIRECTORY/tools/probe.png" > /dev/null 2>&1; then
+ echo "flatpak-validate-icon loads images here and checks the icons in full"
+else
+ icon_check="fallback"
+ {
+ printf '#!%s -I\n' "$(command -v python3)"
+ cat <<'EOF'
+# Checks an icon for flatpak build-export in place of flatpak-validate-icon, with the same arguments:
+# [--sandbox] MAX_WIDTH MAX_HEIGHT PATH. It reads the format and the size, but does not decode the image.
+import struct
+import sys
+import xml.etree.ElementTree as ElementTree
+
+arguments = [argument for argument in sys.argv[1:] if argument != "--sandbox"]
+if len(arguments) != 3:
+ sys.exit("Usage: validate-icon [--sandbox] MAX_WIDTH MAX_HEIGHT PATH")
+
+max_width, max_height, path = int(arguments[0]), int(arguments[1]), arguments[2]
+with open(path, "rb") as icon:
+ head = icon.read(24)
+
+if len(head) == 24 and head[:8] == b"\x89PNG\r\n\x1a\n" and head[12:16] == b"IHDR":
+ width, height = struct.unpack(">II", head[16:24])
+ if width > max_width or height > max_height:
+ sys.exit(f"Image too large ({width}x{height}). Max. size {max_width}x{max_height}")
+
+ sys.exit(0)
+
+try:
+ if ElementTree.parse(path).getroot().tag.rpartition("}")[2] == "svg":
+ sys.exit(0)
+except ElementTree.ParseError:
+ pass
+
+sys.exit("Format not recognized by the fallback check, which knows PNG and SVG only")
+EOF
+ } > "$BUILD_DIRECTORY/tools/validate-icon"
+ chmod 755 "$BUILD_DIRECTORY/tools/validate-icon"
+ export FLATPAK_VALIDATE_ICON="$BUILD_DIRECTORY/tools/validate-icon"
+ echo "flatpak-validate-icon cannot load images here, e.g., under Rosetta, since glycin needs seccomp"
+ echo "The export checks the format and the size of the icons instead, without decoding them"
+fi
+
if [ "$SOURCE" = "local" ]; then
stage "Committing the local checkout in a repository of its own"
@@ -253,4 +321,7 @@ flatpak build-bundle \
"$(yq -r '.branch' "$PANDOC_MANIFEST")"
stage "Done"
-ls -l "$OUT_DIRECTORY"
\ No newline at end of file
+ls -l "$OUT_DIRECTORY"
+if [ "$icon_check" = "fallback" ]; then
+ echo "Note: the icons got only the fallback check, see 'Checking the icon validator'. The CI of the Flatpak repository and Flathub check them in full."
+fi
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Assistants/BeyondFactsLab/BflMaterialService.cs b/app/MindWork AI Studio/Assistants/BeyondFactsLab/BflMaterialService.cs
index c05b3a459..b23eedf09 100644
--- a/app/MindWork AI Studio/Assistants/BeyondFactsLab/BflMaterialService.cs
+++ b/app/MindWork AI Studio/Assistants/BeyondFactsLab/BflMaterialService.cs
@@ -376,10 +376,7 @@ public sealed class BflMaterialService(BeyondFactsLabStore store, RustService ru
return FileExtractionResult.Failed(FileExtractionErrorCode.INVALID_REQUEST, "No transcription provider may hear the recordings of the BeyondFacts Lab.");
}
- if (SettingsManager.DataDirectory is not { } dataDirectory)
- return FileExtractionResult.Failed(FileExtractionErrorCode.INTERNAL, "The data directory of AI Studio is not known yet.");
-
- var location = new BflTranscriptLocation(dataDirectory);
+ var location = new BflTranscriptLocation();
try
{
var transcript = await PersistentMediaTranscript.ReadOrCreateAsync(location, path, provider, mediaTranscriptionService.TranscribeAsync, logger, CancellationToken.None);
diff --git a/app/MindWork AI Studio/Assistants/BeyondFactsLab/BflTranscriptLocation.cs b/app/MindWork AI Studio/Assistants/BeyondFactsLab/BflTranscriptLocation.cs
index bf9dc8dc4..64772aa78 100644
--- a/app/MindWork AI Studio/Assistants/BeyondFactsLab/BflTranscriptLocation.cs
+++ b/app/MindWork AI Studio/Assistants/BeyondFactsLab/BflTranscriptLocation.cs
@@ -7,18 +7,12 @@ namespace AIStudio.Assistants.BeyondFactsLab;
///
///
/// The lab keeps only the filtered text of a transcript, as the text of the material. The transcript itself lies in
-/// a folder of its own below media-staging of the data directory, which the lab deletes once it has read the
-/// transcript; whatever a crash leaves there, TranscriptStagingCleanupService removes with the next start. Backups
-/// leave that folder out.
+/// a folder of its own in the temporary folder of AI Studio, which the lab deletes once it has read the transcript;
+/// whatever a crash leaves there is gone with the next start of AI Studio, see TemporaryFiles. Backups leave that
+/// folder out.
///
-/// The data directory of AI Studio.
-internal sealed class BflTranscriptLocation(string dataDirectory) : IMediaTranscriptLocation
+internal sealed class BflTranscriptLocation : IMediaTranscriptLocation
{
- ///
- /// The folder of the data directory for transcripts on their way, shared with the chat; see TranscriptStagingCleanupService.
- ///
- private const string STAGING_DIRECTORY_NAME = "media-staging";
-
///
/// The name of the transcript in its folder.
///
@@ -27,7 +21,7 @@ internal sealed class BflTranscriptLocation(string dataDirectory) : IMediaTransc
///
/// Gets the folder of this transcript, which no other one shares.
///
- public string FolderPath { get; } = Path.Combine(dataDirectory, STAGING_DIRECTORY_NAME, $"bfl-{Guid.NewGuid():N}");
+ public string FolderPath { get; } = TemporaryFiles.CreateDirectory();
///
public Task ResolveAsync(string mediaPath, CancellationToken token)
diff --git a/app/MindWork AI Studio/Assistants/I18N/allTexts.lua b/app/MindWork AI Studio/Assistants/I18N/allTexts.lua
index 738f71d9d..6a3df9c73 100644
--- a/app/MindWork AI Studio/Assistants/I18N/allTexts.lua
+++ b/app/MindWork AI Studio/Assistants/I18N/allTexts.lua
@@ -20086,6 +20086,12 @@ UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T1133173666"] = "The provider
-- The provider '{0}' refused the request. Your account might not be allowed to use the selected model, or the provider might not serve your region.
UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T1133173666::INFORMAL"] = "The provider '{0}' refused the request. Your account might not be allowed to use the selected model, or the provider might not serve your region."
+-- AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again.
+UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T171993942"] = "AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again."
+
+-- AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again.
+UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T171993942::INFORMAL"] = "AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again."
+
-- Tried to stream the LLM provider '{0}' answer. Was not able to read the stream. The message is: '{1}'
UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T1856278860"] = "Tried to stream the LLM provider '{0}' answer. Was not able to read the stream. The message is: '{1}'"
diff --git a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.cs b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.cs
index baf1c6495..5ffd5f16d 100644
--- a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.cs
+++ b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.cs
@@ -143,6 +143,8 @@ public partial class VisualBriefingAssistant : MSGComponentBase
///
protected override async Task OnInitializedAsync()
{
+ // Taken before the first await: Blazor may dispose the page meanwhile, see "Loops of a component" in app/AGENTS.md:
+ var sourceMonitorToken = this.sourceMonitorCancellation.Token;
await base.OnInitializedAsync();
if (!this.SettingsManager.IsAssistantVisible(
ComponentKind.VISUAL_BRIEFING_ASSISTANT,
@@ -158,7 +160,10 @@ public partial class VisualBriefingAssistant : MSGComponentBase
this.BuildProgressService.Changed += this.BuildProgressChanged;
await this.ReloadListAsync();
await this.ConsumePendingMediaOutcomesAsync();
- this.MonitorSourceStatusAsync(this.sourceMonitorCancellation.Token).Observe($"{nameof(VisualBriefingAssistant)}: monitoring the source status");
+ if (sourceMonitorToken.IsCancellationRequested)
+ return;
+
+ this.MonitorSourceStatusAsync(sourceMonitorToken).Observe($"{nameof(VisualBriefingAssistant)}: monitoring the source status");
if (AssistantLaunchService.TakeTextPayload(ComponentKind.VISUAL_BRIEFING_ASSISTANT) is { } textLaunchPayload && !string.IsNullOrWhiteSpace(textLaunchPayload.Text))
{
// A text sent here starts a briefing of its own, which holds what the text demands. The briefing
diff --git a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingBuildProgress.razor.cs b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingBuildProgress.razor.cs
index a7b334936..becb8cffe 100644
--- a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingBuildProgress.razor.cs
+++ b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingBuildProgress.razor.cs
@@ -55,8 +55,11 @@ public partial class VisualBriefingBuildProgress : MSGComponentBase
protected override async Task OnInitializedAsync()
{
+ // Taken before the first await: Blazor may dispose the component meanwhile, see "Loops of a component" in app/AGENTS.md:
+ var durationMonitorToken = this.durationMonitorCancellation.Token;
await base.OnInitializedAsync();
- this.MonitorBuildDurationAsync(this.durationMonitorCancellation.Token).Observe($"{nameof(VisualBriefingBuildProgress)}: monitoring the build duration");
+ if (!durationMonitorToken.IsCancellationRequested)
+ this.MonitorBuildDurationAsync(durationMonitorToken).Observe($"{nameof(VisualBriefingBuildProgress)}: monitoring the build duration");
}
protected override void OnParametersSet()
diff --git a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingSourcePreparationService.cs b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingSourcePreparationService.cs
index c69ea6690..e52d094b4 100644
--- a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingSourcePreparationService.cs
+++ b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingSourcePreparationService.cs
@@ -21,9 +21,8 @@ internal sealed class VisualBriefingSourcePreparationService(VisualBriefingStore
/// The prepared sources.
public async Task PrepareAsync(VisualBriefingManifest manifest, Guid operationId, Guid buildId, CancellationToken token)
{
- var temporaryDirectory = Path.Combine(Path.GetTempPath(), $"mwai-visual-briefing-{Guid.NewGuid():N}");
- Directory.CreateDirectory(temporaryDirectory);
-
+ var temporaryDirectory = TemporaryFiles.CreateDirectory();
+
try
{
List attachments = [];
diff --git a/app/MindWork AI Studio/Chat/ManagedTranscriptAttachment.cs b/app/MindWork AI Studio/Chat/ManagedTranscriptAttachment.cs
index 6bbfe69aa..150e836d5 100644
--- a/app/MindWork AI Studio/Chat/ManagedTranscriptAttachment.cs
+++ b/app/MindWork AI Studio/Chat/ManagedTranscriptAttachment.cs
@@ -36,14 +36,13 @@ public sealed record ManagedTranscriptAttachment(string FileName, string FilePat
///
public override FileAttachment WithFilePath(string filePath) => new ManagedTranscriptAttachment(this.FileName, filePath, this.FileSizeBytes, this.OriginalFileName, this.IsStaged) { ProvenanceId = this.ProvenanceId, Version = this.Version };
- /// Creates a transcript in an operation-specific staging directory.
+ /// Creates a transcript in an operation-specific folder of the temporary folder of AI Studio, see TemporaryFiles.
/// Original media path.
/// Provider transcript.
/// The staged managed attachment.
public static async Task CreateStagedAsync(string originalPath, string transcript)
{
- var operationDirectory = Path.Combine(SettingsManager.DataDirectory!, "media-staging", Guid.NewGuid().ToString("N"));
- Directory.CreateDirectory(operationDirectory);
+ var operationDirectory = TemporaryFiles.CreateDirectory();
var originalFileName = Path.GetFileName(originalPath);
var stagingPath = Path.Combine(operationDirectory, $"{Guid.NewGuid():N}.md");
await File.WriteAllTextAsync(stagingPath, BuildMarkdown(originalFileName, transcript), new UTF8Encoding(false));
@@ -82,7 +81,7 @@ public sealed record ManagedTranscriptAttachment(string FileName, string FilePat
return false;
var segments = relative.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
- var isStaging = segments is ["media-staging", _, _]
+ var isStaging = segments is [TemporaryFiles.FOLDER_NAME, _, _]
&& Guid.TryParseExact(segments[1], "N", out _)
&& !string.IsNullOrWhiteSpace(segments[2]);
diff --git a/app/MindWork AI Studio/Components/ElapsedTime.razor.cs b/app/MindWork AI Studio/Components/ElapsedTime.razor.cs
index d39819993..05c2e48bf 100644
--- a/app/MindWork AI Studio/Components/ElapsedTime.razor.cs
+++ b/app/MindWork AI Studio/Components/ElapsedTime.razor.cs
@@ -27,8 +27,11 @@ public partial class ElapsedTime : MSGComponentBase
protected override async Task OnInitializedAsync()
{
+ // Taken before the first await: Blazor may dispose the component meanwhile, see "Loops of a component" in app/AGENTS.md:
+ var tickToken = this.tickCancellation.Token;
await base.OnInitializedAsync();
- this.TickAsync(this.tickCancellation.Token).Observe($"{nameof(ElapsedTime)}: counting the elapsed time");
+ if (!tickToken.IsCancellationRequested)
+ this.TickAsync(tickToken).Observe($"{nameof(ElapsedTime)}: counting the elapsed time");
}
#endregion
diff --git a/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua b/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua
index 7b78aa4dd..9f761c1e1 100644
--- a/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua
+++ b/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua
@@ -20088,6 +20088,12 @@ UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T1133173666"] = "Der Anbieter
-- The provider '{0}' refused the request. Your account might not be allowed to use the selected model, or the provider might not serve your region.
UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T1133173666::INFORMAL"] = "Der Anbieter „{0}“ hat die Anfrage abgelehnt. Möglicherweise ist dein Konto nicht für die Nutzung des ausgewählten Modells berechtigt, oder der Anbieter ist in deiner Region nicht verfügbar."
+-- AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again.
+UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T171993942"] = "AI Studio konnte die Mediendatei nicht an den Anbieter „{0}“ senden, weil die Verbindung zu ihm fehlgeschlagen ist. Bitte versuchen Sie es erneut."
+
+-- AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again.
+UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T171993942::INFORMAL"] = "AI Studio konnte die Mediendatei nicht an den Anbieter „{0}“ senden, weil die Verbindung zu ihm fehlgeschlagen ist. Bitte versuche es erneut."
+
-- Tried to stream the LLM provider '{0}' answer. Was not able to read the stream. The message is: '{1}'
UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T1856278860"] = "Der Versuch, die Antwort des LLM-Anbieters „{0}“ zu streamen, ist fehlgeschlagen. Der Stream konnte nicht gelesen werden. Die Meldung lautet: „{1}“"
diff --git a/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua b/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua
index b5897271e..6a0c2aa24 100644
--- a/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua
+++ b/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua
@@ -20088,6 +20088,12 @@ UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T1133173666"] = "The provider
-- The provider '{0}' refused the request. Your account might not be allowed to use the selected model, or the provider might not serve your region.
UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T1133173666::INFORMAL"] = "The provider '{0}' refused the request. Your account might not be allowed to use the selected model, or the provider might not serve your region."
+-- AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again.
+UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T171993942"] = "AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again."
+
+-- AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again.
+UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T171993942::INFORMAL"] = "AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again."
+
-- Tried to stream the LLM provider '{0}' answer. Was not able to read the stream. The message is: '{1}'
UI_TEXT_CONTENT["AISTUDIO::PROVIDER::BASEPROVIDER::T1856278860"] = "Tried to stream the LLM provider '{0}' answer. Was not able to read the stream. The message is: '{1}'"
diff --git a/app/MindWork AI Studio/Program.cs b/app/MindWork AI Studio/Program.cs
index d50df8c7d..45d5aecdc 100644
--- a/app/MindWork AI Studio/Program.cs
+++ b/app/MindWork AI Studio/Program.cs
@@ -120,6 +120,7 @@ internal sealed class Program
}
var runtimeInfo = await rust.GetRuntimeInfo();
+ var tauriDataDirectory = await rust.GetDataDirectory();
var builder = WebApplication.CreateBuilder();
builder.WebHost.ConfigureKestrel(kestrelServerOptions =>
{
@@ -145,7 +146,6 @@ internal sealed class Program
{
try
{
- var tauriDataDirectory = await rust.GetDataDirectory();
if(string.IsNullOrWhiteSpace(tauriDataDirectory))
throw new InvalidOperationException("Rust returned an empty Tauri data directory.");
@@ -276,7 +276,6 @@ internal sealed class Program
builder.Services.AddTransient();
builder.Services.AddHostedService();
builder.Services.AddHostedService();
- builder.Services.AddHostedService();
builder.Services.AddHostedService();
builder.Services.AddHostedService();
@@ -353,6 +352,10 @@ internal sealed class Program
var programLogger = app.Services.GetRequiredService>();
programLogger.LogInformation("Starting the AI Studio server.");
+ // Before any service runs, since emptying the temporary folder deletes what an operation writes there:
+ var temporaryFilesLogger = LOGGER_FACTORY.CreateLogger(nameof(TemporaryFiles));
+ TemporaryFiles.Initialize(tauriDataDirectory, temporaryFilesLogger);
+
//
// Observe tasks whose exceptions nobody awaited. We register this before the server starts:
// otherwise, everything the startup does — the plugin system, the first message bus traffic —
@@ -432,7 +435,8 @@ internal sealed class Program
programLogger.LogInformation("The AI Studio server is ready.");
await serverTask;
-
+ TemporaryFiles.Clear(temporaryFilesLogger);
+
RUST_SERVICE.Dispose();
DATABASE_CLIENT_PROVIDER.Dispose();
PluginFactory.Dispose();
diff --git a/app/MindWork AI Studio/Provider/BaseProvider.cs b/app/MindWork AI Studio/Provider/BaseProvider.cs
index a4c345a4d..d0f4db89b 100644
--- a/app/MindWork AI Studio/Provider/BaseProvider.cs
+++ b/app/MindWork AI Studio/Provider/BaseProvider.cs
@@ -1757,13 +1757,29 @@ public abstract class BaseProvider : IProvider, ISecretId
}
catch (Exception e)
{
- if (this.IsTimeoutException(e, token))
+ var isTimeout = this.IsTimeoutException(e, token);
+ if (isTimeout)
await this.SendTimeoutError("transcribing audio");
this.logger.LogError(e, "Failed to perform transcription request: '{Message}'.", e.Message);
+ if (!isTimeout && IsConnectionFailure(e))
+ return TranscriptionResult.Failure(string.Format(TA("AI Studio could not send the media file to the provider '{0}', because the connection to it failed. Please try again."), this.NameForUser));
+
return TranscriptionResult.Failure();
}
}
+
+ ///
+ /// Whether a request failed because the connection failed, before the provider answered.
+ ///
+ ///
+ /// This holds when the server cannot be reached and when the connection breaks off while the media file is on its
+ /// way, e.g., when the provider closes it. The file has nothing to do with it, and the same file may go through on
+ /// the next try. Without this distinction, the user reads that the provider could not transcribe the file.
+ ///
+ /// What the request threw.
+ /// True, when the connection failed without an answer of the provider.
+ internal static bool IsConnectionFailure(Exception exception) => exception is HttpRequestException { StatusCode: null };
///
/// The cancellation token is not the last parameter, unlike everywhere else in this codebase:
diff --git a/app/MindWork AI Studio/Tools/DataBackup/DataBackupContents.cs b/app/MindWork AI Studio/Tools/DataBackup/DataBackupContents.cs
index dc2acbe14..2b3f332c2 100644
--- a/app/MindWork AI Studio/Tools/DataBackup/DataBackupContents.cs
+++ b/app/MindWork AI Studio/Tools/DataBackup/DataBackupContents.cs
@@ -1,4 +1,3 @@
-using AIStudio.Tools.OpenXml;
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Tools.DataBackup;
@@ -57,12 +56,9 @@ public static class DataBackupContents
new(DataBackupLocation.DATA_DIRECTORY, "plugins/.config/", DataBackupEntryKind.ORGANIZATION_PLUGINS),
new(DataBackupLocation.DATA_DIRECTORY, "plugins/.config-tests/", DataBackupEntryKind.ORGANIZATION_PLUGINS),
new(DataBackupLocation.DATA_DIRECTORY, "plugins/.lock", DataBackupEntryKind.TEMPORARY_FILES),
- new(DataBackupLocation.DATA_DIRECTORY, ".plugin-staging/", DataBackupEntryKind.TEMPORARY_FILES),
- new(DataBackupLocation.DATA_DIRECTORY, StagedDocument.DIRECTORY, DataBackupEntryKind.TEMPORARY_FILES),
new(DataBackupLocation.DATA_DIRECTORY, ".plugin-install-backups/", DataBackupEntryKind.TEMPORARY_FILES),
new(DataBackupLocation.DATA_DIRECTORY, ".plugin-delete-backups/", DataBackupEntryKind.TEMPORARY_FILES),
- new(DataBackupLocation.DATA_DIRECTORY, "media-staging/", DataBackupEntryKind.TEMPORARY_FILES),
- new(DataBackupLocation.DATA_DIRECTORY, "mailAttachments/", DataBackupEntryKind.TEMPORARY_FILES),
+ new(DataBackupLocation.DATA_DIRECTORY, TemporaryFiles.DIRECTORY, DataBackupEntryKind.TEMPORARY_FILES),
new(DataBackupLocation.DATA_DIRECTORY, "mindwork_ai_studio.pid", DataBackupEntryKind.TEMPORARY_FILES),
new(DataBackupLocation.DATA_DIRECTORY, DataBackupFormat.STAGING_DIRECTORY, DataBackupEntryKind.TEMPORARY_FILES),
new(DataBackupLocation.DATA_DIRECTORY, DataRestoreFormat.PENDING_DIRECTORY, DataBackupEntryKind.TEMPORARY_FILES),
diff --git a/app/MindWork AI Studio/Tools/Databases/IndexStore/IndexStoreDesignTimeDbContextFactory.cs b/app/MindWork AI Studio/Tools/Databases/IndexStore/IndexStoreDesignTimeDbContextFactory.cs
index ec92c7def..749d0247e 100644
--- a/app/MindWork AI Studio/Tools/Databases/IndexStore/IndexStoreDesignTimeDbContextFactory.cs
+++ b/app/MindWork AI Studio/Tools/Databases/IndexStore/IndexStoreDesignTimeDbContextFactory.cs
@@ -7,8 +7,11 @@ internal sealed class IndexStoreDesignTimeDbContextFactory : IDesignTimeDbContex
public IndexStoreDbContext CreateDbContext(string[] args)
{
var databasePath = args.FirstOrDefault(argument => argument.EndsWith(".sqlite3", StringComparison.OrdinalIgnoreCase));
+ // Only dotnet ef runs this, while it creates a migration, so neither AI Studio nor its data directory is there:
+#pragma warning disable MWAIS0019
if (string.IsNullOrWhiteSpace(databasePath))
databasePath = Path.Combine(Path.GetTempPath(), "mindwork-ai-studio-rag-index-design.sqlite3");
+#pragma warning restore MWAIS0019
return new IndexStoreDbContext(IndexStoreDbContext.CreateOptions(databasePath));
}
diff --git a/app/MindWork AI Studio/Tools/Databases/ProvenanceStore/ProvenanceStoreDesignTimeDbContextFactory.cs b/app/MindWork AI Studio/Tools/Databases/ProvenanceStore/ProvenanceStoreDesignTimeDbContextFactory.cs
index 5baefbfd2..bd5105798 100644
--- a/app/MindWork AI Studio/Tools/Databases/ProvenanceStore/ProvenanceStoreDesignTimeDbContextFactory.cs
+++ b/app/MindWork AI Studio/Tools/Databases/ProvenanceStore/ProvenanceStoreDesignTimeDbContextFactory.cs
@@ -7,8 +7,11 @@ internal sealed class ProvenanceStoreDesignTimeDbContextFactory : IDesignTimeDbC
public ProvenanceStoreDbContext CreateDbContext(string[] args)
{
var databasePath = args.FirstOrDefault(argument => argument.EndsWith(".sqlite3", StringComparison.OrdinalIgnoreCase));
+ // Only dotnet ef runs this, while it creates a migration, so neither AI Studio nor its data directory is there:
+#pragma warning disable MWAIS0019
if (string.IsNullOrWhiteSpace(databasePath))
databasePath = Path.Combine(Path.GetTempPath(), "mindwork-ai-studio-provenance-design.sqlite3");
+#pragma warning restore MWAIS0019
return new ProvenanceStoreDbContext(ProvenanceStoreDbContext.CreateOptions(databasePath));
}
diff --git a/app/MindWork AI Studio/Tools/DocumentSegments/AGENTS.md b/app/MindWork AI Studio/Tools/DocumentSegments/AGENTS.md
index 7a8b57d89..ce84594e6 100644
--- a/app/MindWork AI Studio/Tools/DocumentSegments/AGENTS.md
+++ b/app/MindWork AI Studio/Tools/DocumentSegments/AGENTS.md
@@ -58,8 +58,8 @@ the repository root and to `app/AGENTS.md`, which apply here as well.
with the SDK: it reads and writes through a `PackageSkeleton` from `app/MindWork AI Studio/Tools/OpenXml/`, which
holds only the XML of the source. The writer changes the DOM of the skeleton, opened for reading only, and the
skeleton writes a new archive with the changed parts, in which every other entry streams through as it is, a stored
- one stays stored. Skeleton and new document come about in `StagedDocument`s below the data directory, not in the
- temporary folder, and `TargetFile` streams the new document into the file the user chose. A writer therefore changes
+ one stays stored. Skeleton and new document come about in `StagedDocument`s in the temporary folder of AI Studio below the
+ data directory (`TemporaryFiles`), not in the one of the system, and `TargetFile` streams the new document into the file the user chose. A writer therefore changes
only the XML of existing parts and never adds or removes parts or relationships. A new Office format brings only its
reader, its writer, and the element of each paragraph (`ElementOf`).
diff --git a/app/MindWork AI Studio/Tools/OpenXml/StagedDocument.cs b/app/MindWork AI Studio/Tools/OpenXml/StagedDocument.cs
index f7cf1cd72..c29f16d7d 100644
--- a/app/MindWork AI Studio/Tools/OpenXml/StagedDocument.cs
+++ b/app/MindWork AI Studio/Tools/OpenXml/StagedDocument.cs
@@ -1,31 +1,22 @@
-using AIStudio.Settings;
-
namespace AIStudio.Tools.OpenXml;
///
-/// A file below the data directory, in which a new Office document or a piece of it comes about, such as the skeleton
-/// of a document or a picture for it, before the document goes into the file the user chose, see TargetFile.
+/// A file in the temporary folder of AI Studio, in which a new Office document or a piece of it comes about, such as
+/// the skeleton of a document or a picture for it, before the document goes into the file the user chose, see
+/// TargetFile.
///
///
///
-/// The folder lies below the data directory rather than in the temporary folder of the system: on many Linux
-/// systems, the temporary folder lives in memory (tmpfs), and a document with videos takes hundreds of megabytes.
-/// A backup leaves the folder out, see DataBackupContents.
+/// The temporary folder of AI Studio lies below the data directory rather than in the temporary folder of the system:
+/// on many Linux systems, the temporary folder lives in memory (tmpfs), and a document with videos takes hundreds of
+/// megabytes, see TemporaryFiles.
///
///
-/// Disposing the file removes it. A file left behind, e.g., after a crash, is removed by the next document which
-/// comes about here, once it is a day old. Tests, which have no data directory, use the temporary folder.
+/// Disposing the file removes it. A file left behind, e.g., after a crash, is gone with the next start of AI Studio.
///
///
internal sealed class StagedDocument : IDisposable
{
- ///
- /// The folder below the data directory, see DataBackupContents.
- ///
- public const string DIRECTORY = ".document-staging/";
-
- private static readonly TimeSpan AGE_OF_LEFTOVERS = TimeSpan.FromDays(1);
-
private readonly ILogger logger;
private StagedDocument(string filePath, ILogger logger)
@@ -40,19 +31,12 @@ internal sealed class StagedDocument : IDisposable
public string FilePath { get; }
///
- /// Reserves a file for a new document and removes what earlier documents left behind.
+ /// Reserves a file for a new document.
///
/// The extension of the document, including the leading dot.
/// Where to report a file which cannot be removed.
/// The file, which does not exist yet.
- public static StagedDocument Create(string fileExtension, ILogger logger)
- {
- var directory = Path.Join(SettingsManager.DataDirectory ?? Path.GetTempPath(), DIRECTORY);
- Directory.CreateDirectory(directory);
- RemoveLeftovers(directory, logger);
-
- return new StagedDocument(Path.Join(directory, $"{Guid.NewGuid():N}{fileExtension}"), logger);
- }
+ public static StagedDocument Create(string fileExtension, ILogger logger) => new(TemporaryFiles.GetFilePath(fileExtension), logger);
///
/// Streams the complete document into the file the user chose, see TargetFile.WriteOverAsync.
@@ -65,17 +49,4 @@ internal sealed class StagedDocument : IDisposable
/// Removes the file.
///
public void Dispose() => TargetFile.DeleteQuietly(this.FilePath, this.logger);
-
- ///
- /// Removes the files which are older than a day, e.g., after a crash.
- ///
- private static void RemoveLeftovers(string directory, ILogger logger)
- {
- var oldest = DateTime.UtcNow - AGE_OF_LEFTOVERS;
- foreach (var file in new DirectoryInfo(directory).EnumerateFiles())
- {
- if (file.LastWriteTimeUtc < oldest)
- TargetFile.DeleteQuietly(file.FullName, logger);
- }
- }
}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Tools/Pandoc.cs b/app/MindWork AI Studio/Tools/Pandoc.cs
index f8328472a..861a154cb 100644
--- a/app/MindWork AI Studio/Tools/Pandoc.cs
+++ b/app/MindWork AI Studio/Tools/Pandoc.cs
@@ -1,4 +1,5 @@
-using System.Diagnostics;
+using System.ComponentModel;
+using System.Diagnostics;
using System.Formats.Tar;
using System.IO.Compression;
using System.Text.RegularExpressions;
@@ -40,6 +41,16 @@ public static partial class Pandoc
///
private static bool HAS_LOGGED_SUCCESSFUL_CHECK_ONCE;
+ ///
+ /// Tracks whether a missing Pandoc was already logged since the last check which could start it.
+ ///
+ ///
+ /// Most users have no Pandoc until they install it through AI Studio. That is a stable state, not a failure, so
+ /// it is logged once, like . A check which can start Pandoc resets it, so
+ /// that a Pandoc which disappears later shows up in the log again.
+ ///
+ private static bool HAS_LOGGED_MISSING_ONCE;
+
private static readonly HttpClient WEB_CLIENT = new();
private static readonly SemaphoreSlim INSTALLATION_LOCK = new(1, 1);
@@ -78,6 +89,8 @@ public static partial class Pandoc
return new(false, TB("Was not able to check the Pandoc installation."), false, string.Empty, preparedProcess.IsLocal);
}
+ HAS_LOGGED_MISSING_ONCE = false;
+
// Read output streams asynchronously while the process runs (prevents deadlock):
var outputTask = process.StandardOutput.ReadToEndAsync();
var errorTask = process.StandardError.ReadToEndAsync();
@@ -138,12 +151,29 @@ public static partial class Pandoc
if (showMessages)
await MessageBus.INSTANCE.SendError(new(@AppIcons.PANDOC_UNAVAILABLE, TB("Pandoc doesn't seem to be installed.")));
- LOG.LogError(e, "Pandoc availability check failed. This usually means Pandoc is not installed or not in the system PATH.");
+ if (!IsMissingExecutable(e))
+ LOG.LogError(e, "The Pandoc availability check failed, but not because Pandoc is missing.");
+ else if (!HAS_LOGGED_MISSING_ONCE)
+ {
+ LOG.LogInformation("Pandoc is not installed: AI Studio found it neither in its data directory nor on the system PATH.");
+ HAS_LOGGED_MISSING_ONCE = true;
+ }
return new(false, TB("Pandoc doesn't seem to be installed."), false, string.Empty, false);
}
}
+ ///
+ /// Whether starting a process failed because its executable does not exist.
+ ///
+ ///
+ /// Windows reports ERROR_FILE_NOT_FOUND, macOS and Linux report ENOENT; both have the number 2. Any other failure, such as
+ /// a denied access or a damaged executable, means that something exists which cannot be started.
+ ///
+ /// What Process.Start threw.
+ /// True, when the executable does not exist.
+ internal static bool IsMissingExecutable(Exception exception) => exception is Win32Exception { NativeErrorCode: 2 };
+
///
/// Automatically decompresses the latest pandoc archive into AiStudio's data directory
///
@@ -155,17 +185,21 @@ public static partial class Pandoc
var latestVersion = await FetchLatestVersionAsync();
var installDir = await GetPandocDataFolder(rustService);
- var installParentDir = Path.GetDirectoryName(installDir) ?? Path.GetTempPath();
- var stagingDir = Path.Combine(installParentDir, $"pandoc-install-{Guid.NewGuid():N}");
- var pandocTempDownloadFile = Path.GetTempFileName();
-
+ string? downloadDir = null;
+
LOG.LogInformation("Trying to install Pandoc v{0} to '{1}'...", latestVersion, installDir);
-
+
try
{
- if (!Directory.Exists(installParentDir))
- Directory.CreateDirectory(installParentDir);
-
+ //
+ // The archive and the new Pandoc stay in the temporary folder of AI Studio until the new Pandoc is
+ // complete, so an interrupted installation leaves nothing next to the installation. The folder lies
+ // below the data directory, on the same drive as the installation, so the new Pandoc can move there:
+ //
+ downloadDir = TemporaryFiles.CreateDirectory();
+ var pandocTempDownloadFile = Path.Combine(downloadDir, "archive");
+ var stagingDir = Path.Combine(downloadDir, "pandoc");
+
//
// Download the latest Pandoc archive from GitHub:
//
@@ -177,7 +211,10 @@ public static partial class Pandoc
return;
}
- using var response = await WEB_CLIENT.GetAsync(uri);
+ // Only the headers, so the archive goes to the disk instead of into memory. The time limit of the client
+ // then covers the headers alone, so the token keeps it for the whole download:
+ using var downloadTimeout = new CancellationTokenSource(WEB_CLIENT.Timeout);
+ using var response = await WEB_CLIENT.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, downloadTimeout.Token);
if (!response.IsSuccessStatusCode)
{
await MessageBus.INSTANCE.SendError(new(AppIcons.ERROR, TB("AI Studio couldn't install Pandoc because the archive was not found.")));
@@ -188,7 +225,7 @@ public static partial class Pandoc
// Download the archive to the temporary file:
await using (var tempFileStream = File.Create(pandocTempDownloadFile))
{
- await response.Content.CopyToAsync(tempFileStream);
+ await response.Content.CopyToAsync(tempFileStream, downloadTimeout.Token);
await tempFileStream.FlushAsync();
}
@@ -238,10 +275,8 @@ public static partial class Pandoc
}
finally
{
- TryDeleteFile(pandocTempDownloadFile);
-
- if (Directory.Exists(stagingDir))
- await TryDeleteFolderAsync(stagingDir);
+ if (downloadDir is not null)
+ await TryDeleteFolderAsync(downloadDir);
INSTALLATION_LOCK.Release();
}
@@ -337,21 +372,6 @@ public static partial class Pandoc
}
}
- private static void TryDeleteFile(string path)
- {
- if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
- return;
-
- try
- {
- File.Delete(path);
- }
- catch (Exception ex)
- {
- LOG.LogWarning(ex, "Was not able to delete temporary Pandoc archive: '{Path}'.", path);
- }
- }
-
private static async Task TryDeleteFolderAsync(string path)
{
if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
diff --git a/app/MindWork AI Studio/Tools/PandocExport.cs b/app/MindWork AI Studio/Tools/PandocExport.cs
index 3958a8673..2f1b633d1 100644
--- a/app/MindWork AI Studio/Tools/PandocExport.cs
+++ b/app/MindWork AI Studio/Tools/PandocExport.cs
@@ -1,5 +1,4 @@
using System.Diagnostics;
-using System.Text;
using AIStudio.Chat;
using AIStudio.Tools.PluginSystem;
@@ -34,29 +33,21 @@ public static class PandocExport
if (!format.UsesPandoc)
throw new ArgumentOutOfRangeException(nameof(format), format, "Pandoc cannot write this format.");
- var tempMarkdownFilePath = string.Empty;
try
{
- var tempMarkdownFile = Guid.NewGuid().ToString();
- tempMarkdownFilePath = Path.Combine(Path.GetTempPath(), tempMarkdownFile);
-
- // Write text content to a temporary file. Pandoc expects UTF-8 without a byte order
- // mark; a mark would end up as a stray character at the start of the document:
- await File.WriteAllTextAsync(tempMarkdownFilePath, markdownText, new UTF8Encoding(false), token);
-
- // Call Pandoc to create the document:
+ // Call Pandoc to create the document. It reads the text from its standard input, so the text needs no temporary file:
var pandocBuilder = PandocProcessBuilder
.Create()
.UseStandaloneMode()
.WithInputFormat("gfm+emoji+tex_math_dollars")
.WithOutputFormat(format.PandocOutputFormat)
.WithOutputFile(targetFilePath)
- .WithInputFile(tempMarkdownFilePath);
+ .WithStandardInput();
//
// The document is named after the file it is written to. Set as metadata, the name
// reaches the page as a string which Pandoc escapes; only a file named true or false
- // is read as a switch and keeps the temporary name.
+ // is read as a switch, and the page gets the title Pandoc falls back to.
//
if (format.NeedsPageTitle)
pandocBuilder.AddArgument("-M").AddArgument($"pagetitle={Path.GetFileNameWithoutExtension(targetFilePath)}");
@@ -74,6 +65,16 @@ public static class PandocExport
var outputTask = process.StandardOutput.ReadToEndAsync(token);
var errorTask = process.StandardError.ReadToEndAsync(token);
+ try
+ {
+ await using var input = process.StandardInput;
+ await input.WriteAsync(markdownText.AsMemory(), token);
+ }
+ catch (IOException)
+ {
+ // Pandoc stopped reading before the end of the text, e.g., over an invalid argument. Its exit code and error output below tell why.
+ }
+
// Wait for the process to exit AND for streams to be fully read:
await process.WaitForExitAsync(token);
await outputTask;
@@ -93,21 +94,6 @@ public static class PandocExport
LOGGER.LogError(ex, "Error during {ExportFormat} conversion.", format);
return false;
}
- finally
- {
- // Try to remove the temp file:
- if (!string.IsNullOrWhiteSpace(tempMarkdownFilePath))
- {
- try
- {
- File.Delete(tempMarkdownFilePath);
- }
- catch
- {
- LOGGER.LogWarning("Was not able to delete the temporary file '{TempFilePath}'.", tempMarkdownFilePath);
- }
- }
- }
}
///
diff --git a/app/MindWork AI Studio/Tools/PandocProcessBuilder.cs b/app/MindWork AI Studio/Tools/PandocProcessBuilder.cs
index 6cfc457da..82ac443d6 100644
--- a/app/MindWork AI Studio/Tools/PandocProcessBuilder.cs
+++ b/app/MindWork AI Studio/Tools/PandocProcessBuilder.cs
@@ -1,4 +1,5 @@
using System.Diagnostics;
+using System.Text;
using AIStudio.Tools.Rust;
using AIStudio.Tools.Services;
@@ -17,26 +18,33 @@ public sealed class PandocProcessBuilder
// Tracks whether the first log has been written to avoid log spam on repeated calls:
private static bool HAS_LOGGED_ONCE;
- private string? providedInputFile;
private string? providedOutputFile;
private string? providedInputFormat;
private string? providedOutputFormat;
private bool useStandaloneMode;
-
+ private bool readsStandardInput;
+
private readonly List additionalArguments = new();
-
+
private PandocProcessBuilder()
{
}
-
+
public static PandocProcessBuilder Create() => new();
-
- public PandocProcessBuilder WithInputFile(string inputFile)
+
+ ///
+ /// Lets Pandoc read its input from the standard input of the process, in UTF-8 without a byte order mark,
+ /// which Pandoc expects; a mark would end up as a stray character at the start of the document.
+ ///
+ ///
+ /// A text which AI Studio holds anyway thus needs no temporary file, see TemporaryFiles.
+ ///
+ public PandocProcessBuilder WithStandardInput()
{
- this.providedInputFile = inputFile;
+ this.readsStandardInput = true;
return this;
}
-
+
public PandocProcessBuilder WithOutputFile(string outputFile)
{
this.providedOutputFile = outputFile;
@@ -79,14 +87,17 @@ public sealed class PandocProcessBuilder
CreateNoWindow = true
};
+ if (this.readsStandardInput)
+ {
+ startInfo.RedirectStandardInput = true;
+ startInfo.StandardInputEncoding = new UTF8Encoding(false);
+ }
+
// Use argument tokens instead of a single command string so paths with spaces
// or Unicode characters are passed to Pandoc unchanged on all platforms.
if (this.useStandaloneMode)
startInfo.ArgumentList.Add("--standalone");
- if (!string.IsNullOrWhiteSpace(this.providedInputFile))
- startInfo.ArgumentList.Add(this.providedInputFile);
-
if (!string.IsNullOrWhiteSpace(this.providedInputFormat))
{
startInfo.ArgumentList.Add("-f");
@@ -149,8 +160,9 @@ public sealed class PandocProcessBuilder
}
else if (!Directory.Exists(localInstallationRootDirectory))
{
+ // The usual case until the user installs Pandoc through AI Studio, so no warning:
if (shouldLog)
- LOGGER.LogWarning("The local Pandoc installation directory does not exist: '{LocalInstallationRootDirectory}'.", localInstallationRootDirectory);
+ LOGGER.LogInformation("The local Pandoc installation directory does not exist: '{LocalInstallationRootDirectory}'.", localInstallationRootDirectory);
}
else
{
@@ -223,7 +235,7 @@ public sealed class PandocProcessBuilder
// When no local installation was found, we assume that the pandoc executable is in the system PATH:
//
if (shouldLog)
- LOGGER.LogWarning("Falling back to system PATH for the Pandoc executable: '{ExecutableName}'.", PandocExecutableName);
+ LOGGER.LogInformation("Falling back to system PATH for the Pandoc executable: '{ExecutableName}'.", PandocExecutableName);
return new(PandocExecutableName, false);
}
diff --git a/app/MindWork AI Studio/Tools/PluginSystem/PluginFactory.Download.cs b/app/MindWork AI Studio/Tools/PluginSystem/PluginFactory.Download.cs
index 14b19fb80..aef068f46 100644
--- a/app/MindWork AI Studio/Tools/PluginSystem/PluginFactory.Download.cs
+++ b/app/MindWork AI Studio/Tools/PluginSystem/PluginFactory.Download.cs
@@ -44,15 +44,24 @@ public static partial class PluginFactory
var downloadUrl = $"{serverUrl}/{configPlugId}.zip";
LOG.LogInformation($"Try to download configuration plugin with ID='{configPlugId}' from server='{configServerUrl}' (GET {downloadUrl})");
- var tempDownloadFile = Path.GetTempFileName();
- var stagedDirectory = Path.Join(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, $"{configPlugId}.staging-{Guid.NewGuid():N}");
+ string? downloadDirectory = null;
string? backupDirectory = null;
var wasSuccessful = false;
try
{
await LockHotReloadAsync();
+
+ // In the temporary folder of AI Studio, below the data directory: on the drive of the plugins, so the new configuration can move there:
+ downloadDirectory = TemporaryFiles.CreateDirectory();
+ var tempDownloadFile = Path.Join(downloadDirectory, $"{configPlugId}.zip");
+ var stagedDirectory = Path.Join(downloadDirectory, configPlugId.ToString());
+
using var httpClient = ExternalHttpClientTimeout.CreateHttpClient(ExternalHttpTrustPolicy.ALLOW_CUSTOM_ROOTS_WHEN_HOST_WHITELISTED);
- var response = await httpClient.GetAsync(downloadUrl, cancellationToken);
+ // Only the headers, so the archive goes to the disk instead of into memory. The time limit of the client
+ // then covers the headers alone, so the token keeps it for the whole download:
+ using var downloadTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ downloadTimeout.CancelAfter(httpClient.Timeout);
+ using var response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead, downloadTimeout.Token);
if (!response.IsSuccessStatusCode)
{
LOG.LogError($"Failed to download the enterprise configuration plugin. HTTP Status: {response.StatusCode}");
@@ -61,7 +70,7 @@ public static partial class PluginFactory
await using(var tempFileStream = File.Create(tempDownloadFile))
{
- await response.Content.CopyToAsync(tempFileStream, cancellationToken);
+ await response.Content.CopyToAsync(tempFileStream, downloadTimeout.Token);
}
await ExtractConfigPluginArchiveAsync(tempDownloadFile, stagedDirectory, cancellationToken);
@@ -73,7 +82,7 @@ public static partial class PluginFactory
Directory.Move(configDirectory, backupDirectory);
}
- Directory.Move(stagedDirectory, configDirectory);
+ MoveDeploymentIntoPlace(stagedDirectory, configDirectory);
if (!string.IsNullOrWhiteSpace(backupDirectory) && Directory.Exists(backupDirectory))
Directory.Delete(backupDirectory, true);
@@ -99,36 +108,39 @@ public static partial class PluginFactory
}
finally
{
- if (Directory.Exists(stagedDirectory))
+ if (downloadDirectory is not null && Directory.Exists(downloadDirectory))
{
try
{
- Directory.Delete(stagedDirectory, true);
+ Directory.Delete(downloadDirectory, true);
}
catch (Exception e)
{
- LOG.LogError(e, "Failed to delete the staged configuration plugin directory.");
+ LOG.LogError(e, "Failed to delete the downloaded configuration plugin. The next start of AI Studio deletes it.");
}
}
- if (File.Exists(tempDownloadFile))
- {
- try
- {
- File.Delete(tempDownloadFile);
- }
- catch (Exception e)
- {
- LOG.LogError(e, "Failed to delete the temporary download file.");
- }
- }
-
UnlockHotReload();
}
return wasSuccessful;
}
+ ///
+ /// Moves a downloaded deployment of an organization from the temporary folder of AI Studio to its place.
+ ///
+ ///
+ /// Unlike unpacking, Directory.Move creates no missing folders above its destination. The folder of the
+ /// deployments is missing on a new installation until the first deployment arrives, and once somebody deleted it.
+ ///
+ /// The unpacked deployment.
+ /// The directory of the deployment, named after its configuration ID. It must not exist.
+ internal static void MoveDeploymentIntoPlace(string stagedDirectory, string deploymentDirectory)
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(deploymentDirectory)!);
+ Directory.Move(stagedDirectory, deploymentDirectory);
+ }
+
private static async Task ExtractConfigPluginArchiveAsync(string sourceArchiveFileName, string destinationDirectory, CancellationToken token)
{
await PluginArchive.ExtractAsync(sourceArchiveFileName, destinationDirectory, token);
diff --git a/app/MindWork AI Studio/Tools/PluginSystem/PluginFactory.Remove.cs b/app/MindWork AI Studio/Tools/PluginSystem/PluginFactory.Remove.cs
index b63809f30..4a615f917 100644
--- a/app/MindWork AI Studio/Tools/PluginSystem/PluginFactory.Remove.cs
+++ b/app/MindWork AI Studio/Tools/PluginSystem/PluginFactory.Remove.cs
@@ -29,8 +29,12 @@ public static partial class PluginFactory
{
var directoryName = Path.GetFileName(configurationDirectory);
- // A download in flight stages and backs up next to the configuration directories. Those
- // directories belong to a running update, not to a withdrawn configuration:
+ //
+ // A download in flight backs up the previous configuration next to the configuration
+ // directories. Such a directory belongs to a running update, not to a withdrawn
+ // configuration. Earlier versions also staged the new configuration here; what they left
+ // behind goes the way of every other directory which is no configuration:
+ //
if (IsTransientDownloadDirectory(directoryName))
continue;
@@ -50,9 +54,7 @@ public static partial class PluginFactory
/// Checks whether a directory below the enterprise configuration directory belongs to a running
/// download instead of to an installed configuration.
///
- private static bool IsTransientDownloadDirectory(string directoryName) =>
- directoryName.Contains(".staging-", StringComparison.OrdinalIgnoreCase) ||
- directoryName.Contains(".backup-", StringComparison.OrdinalIgnoreCase);
+ private static bool IsTransientDownloadDirectory(string directoryName) => directoryName.Contains(".backup-", StringComparison.OrdinalIgnoreCase);
///
/// Unloads every plugin stored in the given directory and deletes the directory afterwards.
diff --git a/app/MindWork AI Studio/Tools/Services/DataSourceEmbeddingService.cs b/app/MindWork AI Studio/Tools/Services/DataSourceEmbeddingService.cs
index 0939c33c2..41525e212 100644
--- a/app/MindWork AI Studio/Tools/Services/DataSourceEmbeddingService.cs
+++ b/app/MindWork AI Studio/Tools/Services/DataSourceEmbeddingService.cs
@@ -1052,8 +1052,6 @@ public sealed partial class DataSourceEmbeddingService(SettingsManager settingsM
if (!await WaitForFirstPluginLoadAsync(PluginFactory.FirstLoadCompleted, FIRST_PLUGIN_LOAD_TIMEOUT, token))
logger.LogWarning("The plugins were not loaded within {TimeoutSeconds:F0} seconds. Indexing starts with the settings as they are, without what the configuration of an organization may add later.", FIRST_PLUGIN_LOAD_TIMEOUT.TotalSeconds);
- // Before the first run: from then on, a sync may be writing an attachment there.
- MailAttachmentFiles.DeleteLeftovers(logger);
await this.DeleteOrphanedMailboxIndexesAsync(token);
logger.LogInformation("Embedding background service is ready. Running the initial persisted hash check before activating file watchers.");
diff --git a/app/MindWork AI Studio/Tools/Services/Indexing/MailAttachmentFiles.cs b/app/MindWork AI Studio/Tools/Services/Indexing/MailAttachmentFiles.cs
index a1c67e6fc..0a207c6d2 100644
--- a/app/MindWork AI Studio/Tools/Services/Indexing/MailAttachmentFiles.cs
+++ b/app/MindWork AI Studio/Tools/Services/Indexing/MailAttachmentFiles.cs
@@ -1,5 +1,3 @@
-using AIStudio.Settings;
-
namespace AIStudio.Tools.Services.Indexing;
///
@@ -10,27 +8,18 @@ namespace AIStudio.Tools.Services.Indexing;
/// for as long as its text is read, and is deleted right after. Their names are random: the
/// runtime logs the path it reads, and the name of an attachment may name a person.
///
-/// Whatever a crash left behind is deleted when AI Studio starts again, before the first mailbox
-/// is synced. That is why the files live in a directory of their own within the data directory of
-/// AI Studio, rather than in the temporary directory of the OS: deleting everything in it touches
-/// no file of another program.
+/// The files lie in the temporary folder of AI Studio, see TemporaryFiles. Whatever a crash left
+/// behind is deleted when AI Studio starts again.
///
internal static class MailAttachmentFiles
{
- private const string DIRECTORY_NAME = "mailAttachments";
-
///
- /// Makes up the path of a file for one attachment, and creates the directory it lies in.
+ /// Makes up the path of a file for one attachment.
///
/// The extension of the attachment, checked against the known document types beforehand, without a dot.
/// The path, where no file exists yet.
- /// The data directory is not known yet.
- public static string CreatePath(string extension)
- {
- var directory = GetDirectory() ?? throw new InvalidOperationException("The data directory is not known yet.");
- Directory.CreateDirectory(directory);
- return Path.Join(directory, $"{Guid.NewGuid():N}.{extension}");
- }
+ /// AI Studio has not set its temporary folder yet.
+ public static string CreatePath(string extension) => TemporaryFiles.GetFilePath($".{extension}");
///
/// Deletes the file of one attachment, should it exist.
@@ -48,31 +37,4 @@ internal static class MailAttachmentFiles
logger.LogWarning(exception, "The temporary file '{Path}' of a mail attachment could not be deleted. It is deleted on the next start.", path);
}
}
-
- ///
- /// Deletes every file an earlier session of AI Studio left behind.
- ///
- ///
- /// Only to be called before any mailbox is synced, since it deletes the files of a running sync as well.
- ///
- /// The logger.
- public static void DeleteLeftovers(ILogger logger)
- {
- if (GetDirectory() is not { } directory || !Directory.Exists(directory))
- return;
-
- try
- {
- Directory.Delete(directory, true);
- logger.LogInformation("Deleted the temporary files of mail attachments an earlier session left behind.");
- }
- catch (Exception exception)
- {
- logger.LogWarning(exception, "The temporary files of mail attachments in '{Directory}' could not be deleted.", directory);
- }
- }
-
- private static string? GetDirectory() => string.IsNullOrWhiteSpace(SettingsManager.DataDirectory)
- ? null
- : Path.Join(SettingsManager.DataDirectory, DIRECTORY_NAME);
}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Tools/Services/MediaTranscriptionService.cs b/app/MindWork AI Studio/Tools/Services/MediaTranscriptionService.cs
index 9e3e6bf96..63528790e 100644
--- a/app/MindWork AI Studio/Tools/Services/MediaTranscriptionService.cs
+++ b/app/MindWork AI Studio/Tools/Services/MediaTranscriptionService.cs
@@ -498,8 +498,8 @@ public sealed class MediaTranscriptionService(
/// A typed terminal result.
private async Task TranscribeCoreAsync(string mediaPath, MediaOperation operation, bool updateImportState, TranscriptionProvider? checkedProvider = null)
{
- var normalizedPath = Path.Combine(Path.GetTempPath(), "mindwork-ai-studio-media", $"{operation.Id:N}.webm");
- Directory.CreateDirectory(Path.GetDirectoryName(normalizedPath)!);
+ // Hours of a recording take hundreds of megabytes, see TemporaryFiles:
+ var normalizedPath = TemporaryFiles.GetFilePath(".webm");
// Logged next to the operation ID: users recognize the file they picked, whereas an ID only
// helps when correlating log lines. The name alone is enough and keeps full paths out of
@@ -928,7 +928,10 @@ public sealed class MediaTranscriptionService(
try
{
+ // In the temporary folder of the system, unlike the upload: AI Studio empties its own one whenever it starts, and a diagnostic has to outlast a restart:
+#pragma warning disable MWAIS0019
var diagnosticDirectory = Path.Combine(Path.GetTempPath(), "mindwork-ai-studio-media", "diagnostics");
+#pragma warning restore MWAIS0019
Directory.CreateDirectory(diagnosticDirectory);
var diagnosticPath = Path.Combine(diagnosticDirectory, $"{operationId:N}.webm");
File.Move(normalizedPath, diagnosticPath, overwrite: true);
diff --git a/app/MindWork AI Studio/Tools/Services/PluginInstallService.AssistantBuilder.cs b/app/MindWork AI Studio/Tools/Services/PluginInstallService.AssistantBuilder.cs
index c345c835e..a060b715b 100644
--- a/app/MindWork AI Studio/Tools/Services/PluginInstallService.AssistantBuilder.cs
+++ b/app/MindWork AI Studio/Tools/Services/PluginInstallService.AssistantBuilder.cs
@@ -84,7 +84,7 @@ public sealed partial class PluginInstallService
return PluginValidationResult.Failure(TB("The plugin system is not initialized yet."));
var pluginCode = lua.Trim();
- if (!this.TryCreateStagingDirectory(ASSISTANT_BUILDER_DIRECTORY_PREFIX, out var stagingDirectory, out var stagingIssue))
+ if (!this.TryCreateStagingDirectory(out var stagingDirectory, out var stagingIssue))
return PluginValidationResult.Failure(stagingIssue);
try
diff --git a/app/MindWork AI Studio/Tools/Services/PluginInstallService.FileSystem.cs b/app/MindWork AI Studio/Tools/Services/PluginInstallService.FileSystem.cs
index 847daf500..5ee7c6f45 100644
--- a/app/MindWork AI Studio/Tools/Services/PluginInstallService.FileSystem.cs
+++ b/app/MindWork AI Studio/Tools/Services/PluginInstallService.FileSystem.cs
@@ -8,70 +8,43 @@ public sealed partial class PluginInstallService
/// Creates a staging directory for a plugin that is about to be installed.
///
///
- /// The staging directory lives below the data directory, never below the temporary directory of
- /// the operating system. Installing means moving the staged plugin into the plugins directory,
- /// and a directory move cannot cross a file system boundary. Flatpak is the case where this
- /// always applies: its temporary directory is a tmpfs inside the sandbox, while the data
- /// directory lives in the home directory of the user.
+ /// The staging directory lives in the temporary folder of AI Studio below the data directory
+ /// (TemporaryFiles), never below the temporary directory of the operating system. Installing means
+ /// moving the staged plugin into the plugins directory, and a directory move cannot cross a file
+ /// system boundary. Flatpak is the case where this always applies: its temporary directory is a
+ /// tmpfs inside the sandbox, while the data directory lives in the home directory of the user.
+ /// Whatever a crash leaves behind is gone with the next start of AI Studio.
/// It lives next to the plugins directory, not inside it: the plugin loader searches the plugins
/// directory recursively, so a half-written plugin there would be loaded while it is still being
/// staged.
///
- /// The prefix of the staging directory name, naming the caller.
/// The created staging directory.
/// A user-facing issue when the staging directory could not be created.
/// True when the staging directory exists, false otherwise.
- private bool TryCreateStagingDirectory(string prefix, out string stagingDirectory, out string issue)
+ private bool TryCreateStagingDirectory(out string stagingDirectory, out string issue)
{
stagingDirectory = string.Empty;
issue = string.Empty;
- var dataDirectory = SettingsManager.DataDirectory;
- if (string.IsNullOrWhiteSpace(dataDirectory))
+ if (string.IsNullOrWhiteSpace(SettingsManager.DataDirectory))
{
issue = TB("The AI Studio data directory is not initialized yet.");
return false;
}
- var stagingRoot = Path.Join(dataDirectory, STAGING_DIRECTORY);
try
{
- Directory.CreateDirectory(stagingRoot);
- this.CleanUpExpiredStagingDirectories(stagingRoot);
-
- stagingDirectory = Path.Join(stagingRoot, $"{prefix}.staging-{Guid.NewGuid():N}");
- Directory.CreateDirectory(stagingDirectory);
+ stagingDirectory = TemporaryFiles.CreateDirectory();
return true;
}
catch (Exception e)
{
- this.logger.LogError(e, "Failed to create the plugin staging directory below '{StagingRoot}'.", stagingRoot);
- stagingDirectory = string.Empty;
+ this.logger.LogError(e, "Failed to create the plugin staging directory in the temporary folder of AI Studio.");
issue = string.Format(TB("Unexpected error: {0}"), e.Message);
return false;
}
}
- ///
- /// Removes staging directories which an earlier installation left behind, e.g. after a crash.
- ///
- private void CleanUpExpiredStagingDirectories(string stagingRoot)
- {
- var expiry = DateTime.UtcNow.AddHours(-STAGING_RETENTION_HOURS);
- foreach (var leftOverDirectory in Directory.EnumerateDirectories(stagingRoot, "*", SearchOption.TopDirectoryOnly))
- {
- try
- {
- if (Directory.GetLastWriteTimeUtc(leftOverDirectory) < expiry)
- Directory.Delete(leftOverDirectory, true);
- }
- catch (Exception e)
- {
- this.logger.LogWarning(e, "Failed to delete the left-over plugin staging directory '{StagingDirectory}'.", leftOverDirectory);
- }
- }
- }
-
///
/// Moves a directory and falls back to copying it when the move crosses a file system boundary.
///
diff --git a/app/MindWork AI Studio/Tools/Services/PluginInstallService.Import.cs b/app/MindWork AI Studio/Tools/Services/PluginInstallService.Import.cs
index 9eba7fba1..1d1a755f5 100644
--- a/app/MindWork AI Studio/Tools/Services/PluginInstallService.Import.cs
+++ b/app/MindWork AI Studio/Tools/Services/PluginInstallService.Import.cs
@@ -42,7 +42,7 @@ public sealed partial class PluginInstallService
try
{
token.ThrowIfCancellationRequested();
- if (!this.TryCreateStagingDirectory(PLUGIN_IMPORT_DIRECTORY_PREFIX, out stagingDirectory, out var stagingIssue))
+ if (!this.TryCreateStagingDirectory(out stagingDirectory, out var stagingIssue))
return Error(stagingIssue);
await PluginArchive.ExtractAsync(archivePath, stagingDirectory, token);
diff --git a/app/MindWork AI Studio/Tools/Services/PluginInstallService.cs b/app/MindWork AI Studio/Tools/Services/PluginInstallService.cs
index 818f666f1..eb4fe41f5 100644
--- a/app/MindWork AI Studio/Tools/Services/PluginInstallService.cs
+++ b/app/MindWork AI Studio/Tools/Services/PluginInstallService.cs
@@ -24,12 +24,8 @@ public sealed partial class PluginInstallService
private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(PluginInstallService).Namespace, nameof(PluginInstallService));
private const string PLUGIN_FILE_NAME = "plugin.lua";
- private const string ASSISTANT_BUILDER_DIRECTORY_PREFIX = "assistant-builder";
- private const string PLUGIN_IMPORT_DIRECTORY_PREFIX = "plugin-import";
private const string DELETE_BACKUP_DIRECTORY = ".plugin-delete-backups";
private const string INSTALL_BACKUP_DIRECTORY = ".plugin-install-backups";
- private const string STAGING_DIRECTORY = ".plugin-staging";
- private const int STAGING_RETENTION_HOURS = 24;
private const int DIRECTORY_PREFIX_MAX_LEN = 80;
private readonly ILogger logger;
diff --git a/app/MindWork AI Studio/Tools/Services/PluginShareService.cs b/app/MindWork AI Studio/Tools/Services/PluginShareService.cs
index fb52e12ef..06647ee5b 100644
--- a/app/MindWork AI Studio/Tools/Services/PluginShareService.cs
+++ b/app/MindWork AI Studio/Tools/Services/PluginShareService.cs
@@ -17,13 +17,6 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
private const string PLUGIN_FILE_NAME = "plugin.lua";
- ///
- /// Keep in sync with SHARE_DIRECTORY_NAME in runtime/src/share_sheet.rs: the runtime only hands
- /// archives from a directory with this name to the native share sheet.
- ///
- private const string TEMPORARY_ARCHIVE_DIRECTORY = "mindwork-ai-studio-plugin-shares";
-
- private const int TEMPORARY_ARCHIVE_RETENTION_HOURS = 24;
private const int FILE_NAME_PREFIX_MAX_LEN = 80;
///
@@ -37,8 +30,8 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
/// The archive contains the plugin root contents, so plugin.lua is located at the archive root.
///
///
- /// On Windows and macOS, the archive is created in a temporary directory and handed over to the
- /// native share sheet. Linux has no such share sheet, since the XDG desktop portals do not provide
+ /// On Windows and macOS, the archive is created in the temporary folder of AI Studio and handed over
+ /// to the native share sheet. Linux has no such share sheet, since the XDG desktop portals do not provide
/// a share interface. Thus, the archive is exported to a location of the user's choice there. The
/// same happens on Windows and macOS once the share sheet failed or did not respond, until AI
/// Studio restarts.
@@ -162,22 +155,25 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
}
///
- /// Creates the plugin archive in a temporary directory and opens the native share sheet for it.
+ /// Creates the plugin archive in the temporary folder of AI Studio and opens the native share sheet for it.
///
+ ///
+ /// The runtime hands only archives from the temporary folder of AI Studio to the share sheet, see
+ /// TemporaryFiles. The archive gets a folder of its own there, so it can carry the name of the plugin,
+ /// which the recipient sees, just like an exported archive.
+ ///
/// The local plugin to archive and share.
/// The validated plugin root directory.
/// Cancellation token for archive creation.
/// The share result, including the retained temporary archive path when successful.
private async Task ShareViaNativeSheetAsync(IAvailablePlugin plugin, string pluginRoot, CancellationToken token)
{
- var archiveDirectory = Path.Join(Path.GetTempPath(), TEMPORARY_ARCHIVE_DIRECTORY);
- var archivePath = Path.Join(archiveDirectory, $"{CreateSafeFileNamePrefix(plugin.Name)}-{plugin.Id:N}-{Guid.NewGuid():N}{PluginArchive.PLUGIN_FILE_EXTENSION}");
-
+ string? archiveDirectory = null;
try
{
token.ThrowIfCancellationRequested();
- Directory.CreateDirectory(archiveDirectory);
- this.CleanUpExpiredArchives(archiveDirectory);
+ archiveDirectory = TemporaryFiles.CreateDirectory();
+ var archivePath = Path.Join(archiveDirectory, $"{CreateSafeFileNamePrefix(plugin.Name)}{PluginArchive.PLUGIN_FILE_EXTENSION}");
await Task.Run(async () =>
{
@@ -194,7 +190,7 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
//
// A share sheet which did not respond may still appear later and ask for the archive.
- // We keep it for that case; the clean-up removes it once it expired:
+ // We keep it for that case; AI Studio deletes it when it quits or starts again:
//
case ShareSheetOutcome.UNRESPONSIVE:
return ShareSheetUnavailable(plugin, TA("The share dialog of your operating system did not respond."));
@@ -202,7 +198,7 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
case ShareSheetOutcome.FAILED:
case ShareSheetOutcome.UNKNOWN:
default:
- this.TryDeleteArchive(archivePath);
+ this.TryDeleteArchiveDirectory(archiveDirectory);
return ShareSheetUnavailable(plugin, TB("The native share dialog could not be opened."));
}
@@ -211,12 +207,12 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
}
catch (OperationCanceledException)
{
- this.TryDeleteArchive(archivePath);
+ this.TryDeleteArchiveDirectory(archiveDirectory);
throw;
}
catch (Exception exception)
{
- this.TryDeleteArchive(archivePath);
+ this.TryDeleteArchiveDirectory(archiveDirectory);
logger.LogError(exception, "Failed to create a share archive for plugin '{PluginName}' ({PluginId}).", plugin.Name, plugin.Id);
return ShareError(plugin, string.Format(TB("Unexpected error: {0}"), exception.Message));
}
@@ -259,23 +255,6 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
return true;
}
- private void CleanUpExpiredArchives(string archiveDirectory)
- {
- var expiry = DateTime.UtcNow.AddHours(-TEMPORARY_ARCHIVE_RETENTION_HOURS);
- foreach (var archivePath in Directory.EnumerateFiles(archiveDirectory, $"*{PluginArchive.PLUGIN_FILE_EXTENSION}", SearchOption.TopDirectoryOnly))
- {
- try
- {
- if (File.GetLastWriteTimeUtc(archivePath) < expiry)
- File.Delete(archivePath);
- }
- catch (Exception exception)
- {
- logger.LogWarning(exception, "Failed to delete expired plugin archive '{ArchivePath}'.", archivePath);
- }
- }
- }
-
private static string CreateSafeFileNamePrefix(string pluginName)
{
var invalidCharacters = Path.GetInvalidFileNameChars().ToHashSet();
@@ -300,6 +279,21 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
return childPath.StartsWith(parentPath, StringComparison.OrdinalIgnoreCase);
}
+ private void TryDeleteArchiveDirectory(string? archiveDirectory)
+ {
+ if (archiveDirectory is null || !Directory.Exists(archiveDirectory))
+ return;
+
+ try
+ {
+ Directory.Delete(archiveDirectory, true);
+ }
+ catch (Exception exception)
+ {
+ logger.LogWarning(exception, "Failed to delete the temporary plugin archive in '{ArchiveDirectory}'. AI Studio deletes it when it starts again.", archiveDirectory);
+ }
+ }
+
private void TryDeleteArchive(string archivePath)
{
if (!File.Exists(archivePath))
diff --git a/app/MindWork AI Studio/Tools/Services/TranscriptStagingCleanupService.cs b/app/MindWork AI Studio/Tools/Services/TranscriptStagingCleanupService.cs
deleted file mode 100644
index a4ca3570b..000000000
--- a/app/MindWork AI Studio/Tools/Services/TranscriptStagingCleanupService.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-using AIStudio.Settings;
-
-namespace AIStudio.Tools.Services;
-
-///
-/// One-shot startup service that removes transcript staging left by crashes or forced shutdowns.
-///
-public sealed class TranscriptStagingCleanupService(ILogger logger) : BackgroundService
-{
- /// Waits for the data directory, performs one cleanup pass, and then exits.
- /// Host shutdown token.
- protected override async Task ExecuteAsync(CancellationToken stoppingToken)
- {
- while (string.IsNullOrWhiteSpace(SettingsManager.DataDirectory) && !stoppingToken.IsCancellationRequested)
- await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
-
- if (stoppingToken.IsCancellationRequested)
- return;
-
- var stagingRoot = Path.Combine(SettingsManager.DataDirectory!, "media-staging");
- if (!Directory.Exists(stagingRoot))
- {
- logger.LogInformation("Media transcript staging does not exist; startup cleanup has nothing to remove.");
- return;
- }
-
- var directories = Directory.EnumerateDirectories(stagingRoot).ToArray();
- var files = Directory.EnumerateFiles(stagingRoot).ToArray();
- logger.LogInformation("Media transcript startup cleanup found {DirectoryCount} directories and {FileCount} loose files.", directories.Length, files.Length);
-
- if (directories.Length == 0 && files.Length == 0)
- {
- logger.LogInformation("Media transcript staging is empty.");
- return;
- }
-
- var deletedDirectories = 0;
- var deletedFiles = 0;
- var failures = 0;
-
- foreach (var directory in directories)
- {
- try
- {
- Directory.Delete(directory, true);
- deletedDirectories++;
- logger.LogInformation("Removed orphaned media staging directory '{Directory}'.", directory);
- }
- catch (Exception exception)
- {
- failures++;
- logger.LogWarning(exception, "Could not remove orphaned media staging directory '{Directory}'.", directory);
- }
- }
-
- foreach (var file in files)
- {
- try
- {
- File.Delete(file);
- deletedFiles++;
- logger.LogInformation("Removed orphaned media staging file '{File}'.", file);
- }
- catch (Exception exception)
- {
- failures++;
- logger.LogWarning(exception, "Could not remove orphaned media staging file '{File}'.", file);
- }
- }
-
- logger.LogInformation("Media transcript startup cleanup removed {DirectoryCount} directories and {FileCount} files with {FailureCount} failures.",
- deletedDirectories,
- deletedFiles,
- failures);
- }
-}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Tools/TemporaryFiles.cs b/app/MindWork AI Studio/Tools/TemporaryFiles.cs
new file mode 100644
index 000000000..6719ac7fb
--- /dev/null
+++ b/app/MindWork AI Studio/Tools/TemporaryFiles.cs
@@ -0,0 +1,153 @@
+namespace AIStudio.Tools;
+
+///
+/// The temporary folder of AI Studio below its data directory, for files which live only while AI Studio runs.
+///
+///
+///
+/// AI Studio does not write into the temporary folder of the system. On many Linux systems, that folder lives in
+/// memory (tmpfs). In a Flatpak, it always does, limited to a tenth of the memory, and a recording or a document with
+/// videos takes hundreds of megabytes. Besides, all users of a Linux computer share /tmp, and each of them can read
+/// a file which .NET creates there, whereas the data directory lies in the home folder of the user.
+///
+///
+/// AI Studio empties the folder when it starts, before any service runs, and once more when it stops. A file therefore
+/// lives at most as long as AI Studio runs, and whatever a crash left behind is gone with the next start. Whoever
+/// creates a file or a folder here still deletes it once done, since AI Studio may run for weeks. A backup leaves the
+/// folder out, see DataBackupContents.
+///
+///
+internal static class TemporaryFiles
+{
+ ///
+ /// The name of the folder in the data directory.
+ ///
+ ///
+ /// Keep in sync with TEMPORARY_DIRECTORY_NAME in runtime/src/share_sheet.rs: the runtime hands only plugin
+ /// archives from this folder to the share sheet of the operating system.
+ ///
+ public const string FOLDER_NAME = "tmp";
+
+ ///
+ /// The folder below the data directory, see DataBackupContents.
+ ///
+ public const string DIRECTORY = $"{FOLDER_NAME}/";
+
+ ///
+ /// The folders in which earlier versions of AI Studio kept their temporary files, as patterns of folders directly
+ /// in the data directory.
+ ///
+ ///
+ /// They are deleted on every start, which costs a look per pattern, so that no installation keeps them.
+ ///
+ private static readonly string[] FOLDERS_OF_EARLIER_VERSIONS = ["mailAttachments", "pandoc-install-*", ".document-staging", ".plugin-staging", "media-staging"];
+
+ ///
+ /// Finds the folders of earlier versions also when they are hidden: on Linux and macOS, .NET takes a name which
+ /// begins with a dot for hidden.
+ ///
+ private static readonly EnumerationOptions ALL_FOLDERS = new() { AttributesToSkip = FileAttributes.None };
+
+ private static string? FOLDER_PATH;
+
+ ///
+ /// Sets the folder below the given data directory and empties it, together with the folders of earlier versions.
+ ///
+ ///
+ /// AI Studio calls this once, before any service runs, since emptying the folder deletes what a running operation
+ /// wrote there. Only the first instance of AI Studio starts its server, so a second one never deletes the files of
+ /// the first.
+ ///
+ /// The data directory of AI Studio, as the runtime reports it.
+ /// Where to report a folder which cannot be deleted.
+ public static void Initialize(string dataDirectory, ILogger logger)
+ {
+ // Below a relative path, the folder would lie in the working directory, and emptying it would delete files there:
+ if (!Path.IsPathFullyQualified(dataDirectory))
+ {
+ logger.LogError("The temporary folder of AI Studio is not available, because the data directory '{DataDirectory}' is not an absolute path.", dataDirectory);
+ return;
+ }
+
+ FOLDER_PATH = Path.Join(dataDirectory, FOLDER_NAME);
+ Clear(logger);
+ DeleteFoldersOfEarlierVersions(dataDirectory, logger);
+ }
+
+ ///
+ /// Makes up the path of a new file in the folder.
+ ///
+ /// The extension of the file, including the leading dot.
+ /// The path, where no file exists yet.
+ /// AI Studio has not set the folder yet.
+ public static string GetFilePath(string fileExtension) => Path.Join(GetDirectory(), $"{Guid.NewGuid():N}{fileExtension}");
+
+ ///
+ /// Creates a new, empty folder in the folder, e.g., for files which belong together.
+ ///
+ /// The path of the new folder.
+ /// AI Studio has not set the folder yet.
+ public static string CreateDirectory()
+ {
+ var path = Path.Join(GetDirectory(), Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(path);
+ return path;
+ }
+
+ ///
+ /// Deletes everything in the folder. AI Studio does so when it starts and when it stops.
+ ///
+ /// Where to report a folder which cannot be deleted.
+ public static void Clear(ILogger logger)
+ {
+ if (FOLDER_PATH is not null)
+ Delete(FOLDER_PATH, logger);
+ }
+
+ private static void DeleteFoldersOfEarlierVersions(string dataDirectory, ILogger logger)
+ {
+ if (!Directory.Exists(dataDirectory))
+ return;
+
+ try
+ {
+ foreach (var pattern in FOLDERS_OF_EARLIER_VERSIONS)
+ {
+ foreach (var folder in Directory.EnumerateDirectories(dataDirectory, pattern, ALL_FOLDERS))
+ Delete(folder, logger);
+ }
+ }
+ catch (Exception exception)
+ {
+ logger.LogWarning(exception, "The temporary folders of earlier versions of AI Studio in '{DataDirectory}' could not be looked through. The next start of AI Studio tries again.", dataDirectory);
+ }
+ }
+
+ private static string GetDirectory()
+ {
+ var path = FOLDER_PATH ?? throw new InvalidOperationException("The temporary folder of AI Studio is not set yet.");
+ Directory.CreateDirectory(path);
+ return path;
+ }
+
+ ///
+ /// Deletes a folder with everything in it. A link is removed, but never followed: whatever it points to stays.
+ ///
+ /// The folder.
+ /// Where to report a folder which cannot be deleted, e.g., since a file in it is open.
+ private static void Delete(string path, ILogger logger)
+ {
+ try
+ {
+ var folder = new DirectoryInfo(path);
+ if (folder.LinkTarget is not null)
+ folder.Delete();
+ else if (folder.Exists)
+ folder.Delete(recursive: true);
+ }
+ catch (Exception exception)
+ {
+ logger.LogWarning(exception, "The temporary folder '{Path}' could not be deleted. The next start of AI Studio tries again.", path);
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md
index 4ff3b4d3e..3540fd62e 100644
--- a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md
+++ b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md
@@ -23,6 +23,7 @@
- Improved how AI Studio saves your settings and the projects of the Visual Briefing assistant: it now waits until the data has reached the disk before it replaces the previous version, so that a power failure while saving is far less likely to damage them.
- Improved how AI Studio saves chats: if AI Studio crashes while saving a chat, the chat keeps its previous state instead of becoming unreadable.
- Improved the Slide Assistant with large PowerPoint templates: it no longer loads your template and your pictures into memory at once, neither when it reads the template nor when it saves the presentation, so that large templates with many pictures and videos also work on computers with little memory.
+- Improved how AI Studio handles temporary files, such as the converted audio of a transcription: they now lie in a folder of their own within the data folder of AI Studio, which AI Studio empties when it starts and when you quit it. On many Linux systems and in the Flatpak, the temporary folder of the system lives in memory, so these files no longer take up memory there.
- Improved quitting AI Studio: no matter how you quit, AI Studio now closes your local data sources properly and stops its background server right away.
- Improved the speed of local data sources with many files: when you change, move, or remove a file, AI Studio now finds its passages right away instead of looking through every passage of the data source. Searching a data source while AI Studio indexes it got faster as well. The first time AI Studio opens a data source after the update, it prepares this once.
- Improved the assistants page: you can collapse a category with a click on its heading, and AI Studio remembers it.
@@ -72,6 +73,8 @@
- Fixed the Grammar & Spelling Checker assistant, which left your text unchanged when it was written in another language than the one you selected. The assistant now rewrites such text in the selected language, so the comparison shows every change. Names, quotations, and code stay as they are.
- Fixed the Slide Assistant keeping a video or a sound in the PowerPoint file after the AI removed it from a slide of your template, which made the file needlessly large.
- Fixed the Slide Assistant keeping slides of your template hidden in the PowerPoint file, together with their pictures and videos, when a slide you kept linked to them, such as a table of contents. The file was needlessly large; the links to slides which are no longer there now become plain text.
+- Fixed the Visual Briefing assistant, which sometimes showed no briefings when you opened it, until you switched to another page and back.
+- Fixed the message after a transcription whose connection to the provider broke off: instead of claiming that the provider could not transcribe the file, AI Studio now tells you that the connection failed and that you can try again.
- Upgraded several libraries to improve security.
- Upgraded Tauri to v2.12.7.
- Upgraded MudBlazor to v9.14.0.
diff --git a/app/SourceCodeRules/SourceCodeRules/AnalyzerReleases.Shipped.md b/app/SourceCodeRules/SourceCodeRules/AnalyzerReleases.Shipped.md
index aa9f4f49f..4e5d767af 100644
--- a/app/SourceCodeRules/SourceCodeRules/AnalyzerReleases.Shipped.md
+++ b/app/SourceCodeRules/SourceCodeRules/AnalyzerReleases.Shipped.md
@@ -22,3 +22,4 @@
MWAIS0016 | Style | Error | ClassicExtensionMethodAnalyzer
MWAIS0017 | Usage | Error | IconCatalogAnalyzer
MWAIS0018 | Usage | Error | SystemLineBreakAnalyzer
+ MWAIS0019 | Usage | Error | TemporaryFolderAnalyzer
diff --git a/app/SourceCodeRules/SourceCodeRules/Identifier.cs b/app/SourceCodeRules/SourceCodeRules/Identifier.cs
index dba8ab0ce..268ee2bef 100644
--- a/app/SourceCodeRules/SourceCodeRules/Identifier.cs
+++ b/app/SourceCodeRules/SourceCodeRules/Identifier.cs
@@ -20,4 +20,5 @@ public static class Identifier
public const string CLASSIC_EXTENSION_METHOD_ANALYZER = $"{Tools.ID_PREFIX}0016";
public const string ICON_CATALOG_ANALYZER = $"{Tools.ID_PREFIX}0017";
public const string SYSTEM_LINE_BREAK_ANALYZER = $"{Tools.ID_PREFIX}0018";
+ public const string TEMPORARY_FOLDER_ANALYZER = $"{Tools.ID_PREFIX}0019";
}
\ No newline at end of file
diff --git a/app/SourceCodeRules/SourceCodeRules/UsageAnalyzers/TemporaryFolderAnalyzer.cs b/app/SourceCodeRules/SourceCodeRules/UsageAnalyzers/TemporaryFolderAnalyzer.cs
new file mode 100644
index 000000000..2bb766827
--- /dev/null
+++ b/app/SourceCodeRules/SourceCodeRules/UsageAnalyzers/TemporaryFolderAnalyzer.cs
@@ -0,0 +1,67 @@
+using System.Collections.Immutable;
+
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Diagnostics;
+using Microsoft.CodeAnalysis.Operations;
+
+namespace SourceCodeRules.UsageAnalyzers;
+
+///
+/// Refuses the temporary folder of the system: Path.GetTempPath and Path.GetTempFileName.
+///
+///
+/// On many Linux systems, the temporary folder of the system lives in memory (tmpfs). In a Flatpak, it always does,
+/// limited to a tenth of the memory, and a recording or a document with videos takes hundreds of megabytes there.
+/// Besides, all users of a Linux computer share /tmp. AI Studio therefore keeps its temporary files in a folder of its
+/// own below the data directory, which it empties when it starts and when it stops: TemporaryFiles of the app. Code
+/// which needs the folder of the system all the same, such as a diagnostic which has to outlast a restart, says why
+/// with a pragma.
+///
+#pragma warning disable RS1038
+[DiagnosticAnalyzer(LanguageNames.CSharp)]
+#pragma warning restore RS1038
+public sealed class TemporaryFolderAnalyzer : DiagnosticAnalyzer
+{
+ private const string DIAGNOSTIC_ID = Identifier.TEMPORARY_FOLDER_ANALYZER;
+
+ private const string TITLE = "Temporary files go into the temporary folder of AI Studio";
+
+ private const string MESSAGE_FORMAT = "'Path.{0}' uses the temporary folder of the system, which lives in memory on many Linux systems; use TemporaryFiles instead";
+
+ private const string DESCRIPTION = "The temporary folder of the system lives in memory on many Linux systems and always in a Flatpak, and all users of a Linux computer share it. Use TemporaryFiles, which keeps temporary files below the data directory of AI Studio.";
+
+ private const string CATEGORY = "Usage";
+
+ private static readonly DiagnosticDescriptor RULE = new(DIAGNOSTIC_ID, TITLE, MESSAGE_FORMAT, CATEGORY, DiagnosticSeverity.Error, isEnabledByDefault: true, description: DESCRIPTION);
+
+ public override ImmutableArray SupportedDiagnostics => [RULE];
+
+ public override void Initialize(AnalysisContext context)
+ {
+ // The code block of a .razor file ends up in generated code, and the Razor compiler maps the diagnostic back:
+ context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
+ context.EnableConcurrentExecution();
+ context.RegisterOperationAction(AnalyzeInvocation, OperationKind.Invocation);
+ context.RegisterOperationAction(AnalyzeMethodReference, OperationKind.MethodReference);
+ }
+
+ private static void AnalyzeInvocation(OperationAnalysisContext context)
+ {
+ var invocation = (IInvocationOperation)context.Operation;
+ Report(context, invocation.TargetMethod, invocation.Syntax);
+ }
+
+ private static void AnalyzeMethodReference(OperationAnalysisContext context)
+ {
+ var reference = (IMethodReferenceOperation)context.Operation;
+ Report(context, reference.Method, reference.Syntax);
+ }
+
+ private static void Report(OperationAnalysisContext context, IMethodSymbol method, SyntaxNode syntax)
+ {
+ if (method.Name is not ("GetTempPath" or "GetTempFileName") || method.ContainingType.ToDisplayString() is not "System.IO.Path")
+ return;
+
+ context.ReportDiagnostic(Diagnostic.Create(RULE, syntax.GetLocation(), method.Name));
+ }
+}
\ No newline at end of file
diff --git a/app/Tests/Analyzers/TemporaryFolderAnalyzerTests.cs b/app/Tests/Analyzers/TemporaryFolderAnalyzerTests.cs
new file mode 100644
index 000000000..ddaa9d36e
--- /dev/null
+++ b/app/Tests/Analyzers/TemporaryFolderAnalyzerTests.cs
@@ -0,0 +1,78 @@
+using AIStudio.Tests.Models.Generation;
+
+using SourceCodeRules.UsageAnalyzers;
+
+namespace AIStudio.Tests.Analyzers;
+
+///
+/// Checks that MWAIS0019 refuses the temporary folder of the system and leaves everything else alone.
+///
+///
+/// On many Linux systems, and always in a Flatpak, the temporary folder of the system lives in memory. A file there
+/// takes memory, which nobody notices on a developer computer with plenty of it.
+///
+[TestFixture]
+public sealed class TemporaryFolderAnalyzerTests
+{
+ [TestCase("return Path.GetTempPath();", "GetTempPath", TestName = "Path.GetTempPath")]
+ [TestCase("return Path.GetTempFileName();", "GetTempFileName", TestName = "Path.GetTempFileName")]
+ [TestCase("""return Path.Combine(System.IO.Path.GetTempPath(), "file.md");""", "GetTempPath", TestName = "Path.GetTempPath with its namespace")]
+ [TestCase("Func folder = Path.GetTempPath; return folder();", "GetTempPath", TestName = "Path.GetTempPath as a method group")]
+ public async Task TheTemporaryFolderOfTheSystemIsRefused(string statement, string name)
+ {
+ var reported = await CompilationHarness.AnalyzeAsync(ClassWith(statement), new TemporaryFolderAnalyzer());
+
+ using (Assert.EnterMultipleScope())
+ {
+ Assert.That(reported, Has.Count.EqualTo(1));
+ Assert.That(reported.FirstOrDefault()?.Id, Is.EqualTo("MWAIS0019"));
+ Assert.That(reported.FirstOrDefault()?.GetMessage(), Does.Contain($"'Path.{name}'"));
+ }
+ }
+
+ [TestCase("""return Path.Combine(dataDirectory, "tmp");""", TestName = "Another method of Path")]
+ [TestCase("return Folders.GetTempPath();", TestName = "A method GetTempPath of another type")]
+ [TestCase("return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);", TestName = "Another folder of the system")]
+ public async Task AnythingElseIsLeftAlone(string statement)
+ {
+ var reported = await CompilationHarness.AnalyzeAsync(ClassWith(statement), new TemporaryFolderAnalyzer());
+
+ Assert.That(reported, Is.Empty);
+ }
+
+ [Test]
+ public async Task APragmaWithAReasonLetsItPass()
+ {
+ const string STATEMENT = """
+ // A diagnostic has to outlast a restart:
+ #pragma warning disable MWAIS0019
+ return Path.GetTempPath();
+ #pragma warning restore MWAIS0019
+ """;
+
+ var reported = await CompilationHarness.AnalyzeAsync(ClassWith(STATEMENT), new TemporaryFolderAnalyzer());
+
+ Assert.That(reported, Is.Empty);
+ }
+
+ private static string ClassWith(string statement) =>
+ $$"""
+ using System;
+ using System.IO;
+
+ namespace Sample;
+
+ public static class Folders
+ {
+ public static string GetTempPath() => "/data/tmp";
+ }
+
+ public static class Files
+ {
+ public static string Locate(string dataDirectory)
+ {
+ {{statement}}
+ }
+ }
+ """;
+}
\ No newline at end of file
diff --git a/app/Tests/BeyondFactsLab/BflRecordingTests.cs b/app/Tests/BeyondFactsLab/BflRecordingTests.cs
index 968ddff4a..853488644 100644
--- a/app/Tests/BeyondFactsLab/BflRecordingTests.cs
+++ b/app/Tests/BeyondFactsLab/BflRecordingTests.cs
@@ -74,27 +74,30 @@ public sealed class BflRecordingTests
}
[Test]
- public async Task ATranscriptWaitsInAFolderOfItsOwnBelowTheStaging()
+ public async Task ATranscriptWaitsInAFolderOfItsOwnInTheTemporaryFolder()
{
- var first = new BflTranscriptLocation(this.dataDirectory);
- var second = new BflTranscriptLocation(this.dataDirectory);
+ var first = new BflTranscriptLocation();
+ var second = new BflTranscriptLocation();
var slot = await first.ResolveAsync("/Users/person/Interview.mp3", CancellationToken.None);
- var stagingDirectory = Path.Combine(this.dataDirectory, "media-staging");
+ var temporaryFolder = Path.Join(TestHost.DATA_DIRECTORY, "tmp");
using (Assert.EnterMultipleScope())
{
Assert.That(Path.GetDirectoryName(slot.Path), Is.EqualTo(first.FolderPath));
- Assert.That(Path.GetDirectoryName(first.FolderPath), Is.EqualTo(stagingDirectory), "The cleanup at the start of AI Studio removes only what lies below the staging.");
+ Assert.That(Path.GetDirectoryName(first.FolderPath), Is.EqualTo(temporaryFolder), "AI Studio empties only its temporary folder when it starts.");
Assert.That(second.FolderPath, Is.Not.EqualTo(first.FolderPath), "Two imports would share one transcript.");
Assert.That(slot.Path, Does.Not.Contain("Interview"), "The folder of the person decides nothing in the data directory.");
}
+
+ first.TryDelete();
+ second.TryDelete();
}
[Test]
public async Task DeletingTheLocationRemovesTheTranscript()
{
- var location = new BflTranscriptLocation(this.dataDirectory);
+ var location = new BflTranscriptLocation();
var slot = await location.ResolveAsync("/Users/person/Interview.mp3", CancellationToken.None);
Directory.CreateDirectory(location.FolderPath);
await File.WriteAllTextAsync(slot.Path, "Guten Tag.");
@@ -103,7 +106,7 @@ public sealed class BflRecordingTests
{
Assert.That(location.TryDelete(), Is.True);
Assert.That(Directory.Exists(location.FolderPath), Is.False);
- Assert.That(new BflTranscriptLocation(this.dataDirectory).TryDelete(), Is.True, "A location without a transcript is no failure.");
+ Assert.That(new BflTranscriptLocation().TryDelete(), Is.True, "A location without a transcript is no failure.");
}
}
diff --git a/app/Tests/Chat/ChatDraftTests.cs b/app/Tests/Chat/ChatDraftTests.cs
index 8d5bae87c..1852fc519 100644
--- a/app/Tests/Chat/ChatDraftTests.cs
+++ b/app/Tests/Chat/ChatDraftTests.cs
@@ -21,7 +21,7 @@ public sealed class ChatDraftTests
private static readonly FileAttachment MINUTES = new(FileAttachmentType.DOCUMENT, "minutes.pdf", "/documents/minutes.pdf", 2048);
private static readonly FileAttachmentImage CHART = new("chart.png", "/documents/chart.png", 4096);
private static readonly ManagedTranscriptAttachment TRANSCRIPT = new("meeting-transcript-0001.md", "/data/tempChats/meeting-transcript-0001.md", 512, "meeting.mp4", false);
- private static readonly ManagedTranscriptAttachment STAGED_TRANSCRIPT = new("4f1c.md", "/data/media-staging/4f1c.md", 256, "kickoff.mp4", true);
+ private static readonly ManagedTranscriptAttachment STAGED_TRANSCRIPT = new("4f1c.md", "/data/tmp/0123456789abcdef0123456789abcdef/4f1c.md", 256, "kickoff.mp4", true);
[Test]
public void MirroringTheComposerKeepsATranscriptItDoesNotShowYet()
diff --git a/app/Tests/Chat/ManagedTranscriptAttachmentTests.cs b/app/Tests/Chat/ManagedTranscriptAttachmentTests.cs
index 0371318cd..4a90067ef 100644
--- a/app/Tests/Chat/ManagedTranscriptAttachmentTests.cs
+++ b/app/Tests/Chat/ManagedTranscriptAttachmentTests.cs
@@ -1,5 +1,8 @@
using AIStudio.Chat;
using AIStudio.Settings;
+using AIStudio.Tools;
+
+using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.Chat;
@@ -9,7 +12,7 @@ namespace AIStudio.Tests.Chat;
///
/// A transcript carries a full path, which a chat file edited outside the app may point anywhere. AI
/// Studio therefore deletes a file only where it keeps transcripts itself: in the transcript folder of a
-/// chat, or in the staging area.
+/// chat, or in a folder of its own in the temporary folder of AI Studio.
///
[TestFixture]
[NonParallelizable]
@@ -26,12 +29,16 @@ public sealed class ManagedTranscriptAttachmentTests
this.testDirectory = Path.Combine(Path.GetTempPath(), $"ai-studio-transcripts-{Guid.NewGuid():N}");
Directory.CreateDirectory(this.testDirectory);
SettingsManager.DataDirectory = this.testDirectory;
+
+ // The app sets its temporary folder below the same data directory:
+ TemporaryFiles.Initialize(this.testDirectory, NullLogger.Instance);
}
[TearDown]
public void RemoveDataDirectory()
{
SettingsManager.DataDirectory = this.previousDataDirectory;
+ TemporaryFiles.Initialize(TestHost.DATA_DIRECTORY, NullLogger.Instance);
try
{
@@ -43,6 +50,33 @@ public sealed class ManagedTranscriptAttachmentTests
}
}
+ [Test]
+ public async Task AStagedTranscriptIsDeletedTogetherWithItsFolder()
+ {
+ var transcript = await ManagedTranscriptAttachment.CreateStagedAsync("/Users/person/Kickoff.mp4", "Guten Tag.");
+ var folder = Path.GetDirectoryName(transcript.FilePath)!;
+
+ using (Assert.EnterMultipleScope())
+ {
+ Assert.That(Path.GetDirectoryName(folder), Is.EqualTo(Path.Combine(this.testDirectory, "tmp")), "The transcript waits in the temporary folder of AI Studio.");
+ Assert.That(ManagedTranscriptAttachment.TryDeleteOwnedFile(transcript), Is.True);
+ Assert.That(File.Exists(transcript.FilePath), Is.False);
+ Assert.That(Directory.Exists(folder), Is.False);
+ }
+ }
+
+ [Test]
+ public void AFileDirectlyInTheTemporaryFolderStays()
+ {
+ var file = WriteTranscript(Path.Combine(this.testDirectory, "tmp"));
+
+ using (Assert.EnterMultipleScope())
+ {
+ Assert.That(ManagedTranscriptAttachment.TryDeleteOwnedFile(file), Is.False, "A staged transcript has a folder of its own.");
+ Assert.That(File.Exists(file.FilePath), Is.True);
+ }
+ }
+
[Test]
public void TheTranscriptOfAWorkspaceChatIsDeleted()
{
diff --git a/app/Tests/Provider/ConnectionFailureTests.cs b/app/Tests/Provider/ConnectionFailureTests.cs
new file mode 100644
index 000000000..4ed13f4c7
--- /dev/null
+++ b/app/Tests/Provider/ConnectionFailureTests.cs
@@ -0,0 +1,110 @@
+using System.Net;
+using System.Net.Sockets;
+
+using AIStudio.Provider;
+
+namespace AIStudio.Tests.Provider;
+
+///
+/// Checks which failures of a request count as a failed connection, before the provider answered.
+///
+///
+/// A transcription which fails that way says so, instead of claiming that the provider could not transcribe the file.
+/// The exceptions come from a real HttpClient and a real socket, since only they show how .NET reports a connection
+/// which breaks off while the media file is on its way.
+///
+[TestFixture]
+public sealed class ConnectionFailureTests
+{
+ private static readonly TimeSpan TIME_LIMIT = TimeSpan.FromSeconds(10);
+
+ private static readonly HttpClient HTTP_CLIENT = new();
+
+ [Test]
+ public async Task AConnectionWhichBreaksOffDuringTheUploadCounts()
+ {
+ using var timeout = new CancellationTokenSource(TIME_LIMIT);
+ var listener = new TcpListener(IPAddress.Loopback, 0);
+ listener.Start();
+ try
+ {
+ var server = ResetFirstConnectionAsync(listener, timeout.Token);
+ var failure = await SendMediaFileAsync(AddressOf(listener), timeout.Token);
+ await server;
+
+ Assert.That(BaseProvider.IsConnectionFailure(failure), Is.True, failure.ToString());
+ }
+ finally
+ {
+ listener.Stop();
+ }
+ }
+
+ [Test]
+ public async Task AServerWhichCannotBeReachedCounts()
+ {
+ using var timeout = new CancellationTokenSource(TIME_LIMIT);
+
+ // A port which was free a moment ago and has no listener anymore:
+ var listener = new TcpListener(IPAddress.Loopback, 0);
+ listener.Start();
+ var address = AddressOf(listener);
+ listener.Stop();
+
+ var failure = await SendMediaFileAsync(address, timeout.Token);
+
+ Assert.That(BaseProvider.IsConnectionFailure(failure), Is.True, failure.ToString());
+ }
+
+ [Test]
+ public void AnAnswerOfTheProviderDoesNotCount()
+ {
+ var failure = new HttpRequestException("Response status code does not indicate success: 500 (Internal Server Error).", null, HttpStatusCode.InternalServerError);
+
+ Assert.That(BaseProvider.IsConnectionFailure(failure), Is.False);
+ }
+
+ [Test]
+ public void ATimeoutDoesNotCount()
+ {
+ var failure = new TaskCanceledException("The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.", new TimeoutException());
+
+ Assert.That(BaseProvider.IsConnectionFailure(failure), Is.False);
+ }
+
+ private static Uri AddressOf(TcpListener listener) => new($"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/audio/transcriptions");
+
+ ///
+ /// Accepts one connection, reads the beginning of the request, and closes the connection with a reset, as a
+ /// provider does which drops an upload.
+ ///
+ private static async Task ResetFirstConnectionAsync(TcpListener listener, CancellationToken token)
+ {
+ using var client = await listener.AcceptTcpClientAsync(token);
+ var buffer = new byte[16 * 1_024];
+ _ = await client.GetStream().ReadAsync(buffer, token);
+ client.Client.LingerState = new LingerOption(true, 0);
+ client.Close();
+ }
+
+ ///
+ /// Uploads a media file of several MB, as a transcription request does, and returns what the request threw.
+ ///
+ private static async Task SendMediaFileAsync(Uri address, CancellationToken token)
+ {
+ using var form = new MultipartFormDataContent();
+ form.Add(new ByteArrayContent(new byte[8 * 1_024 * 1_024]), "file", "recording.webm");
+ form.Add(new StringContent("whisper-1"), "model");
+
+ try
+ {
+ using var response = await HTTP_CLIENT.PostAsync(address, form, token);
+ }
+ catch (Exception exception) when (exception is not OperationCanceledException || !token.IsCancellationRequested)
+ {
+ return exception;
+ }
+
+ throw new AssertionException("The request did not fail.");
+ }
+}
\ No newline at end of file
diff --git a/app/Tests/TestHost.cs b/app/Tests/TestHost.cs
index 9668ad21b..abe6145cd 100644
--- a/app/Tests/TestHost.cs
+++ b/app/Tests/TestHost.cs
@@ -1,3 +1,5 @@
+using AIStudio.Tools;
+
using Microsoft.Extensions.Logging.Abstractions;
//
@@ -11,9 +13,21 @@ namespace AIStudio.Tests;
[SetUpFixture]
public sealed class TestHost
{
+ ///
+ /// The data directory of the tests, below which TemporaryFiles keeps its folder.
+ ///
+ public static readonly string DATA_DIRECTORY = Path.Join(Path.GetTempPath(), $"ai-studio-tests-{Guid.NewGuid():N}");
+
[OneTimeSetUp]
public void PrepareStaticApplicationState() => PrepareStaticState();
+ [OneTimeTearDown]
+ public void DeleteDataDirectory()
+ {
+ if (Directory.Exists(DATA_DIRECTORY))
+ Directory.Delete(DATA_DIRECTORY, true);
+ }
+
///
/// Fills the static state of the app which the tests need.
///
@@ -31,5 +45,11 @@ public sealed class TestHost
// that writes nowhere is all it takes to get past that.
//
Program.LOGGER_FACTORY = NullLoggerFactory.Instance;
+
+ //
+ // The app sets its temporary folder below its data directory while it starts. The tests have no
+ // data directory, so the folder lies below one of their own:
+ //
+ TemporaryFiles.Initialize(DATA_DIRECTORY, NullLogger.Instance);
}
}
\ No newline at end of file
diff --git a/app/Tests/Tests.csproj b/app/Tests/Tests.csproj
index eb8726a50..beef7d2e3 100644
--- a/app/Tests/Tests.csproj
+++ b/app/Tests/Tests.csproj
@@ -52,7 +52,7 @@
the tests, too, until it is listed here.
-->
- $(NoWarn);MWAIS0001;MWAIS0002;MWAIS0003;MWAIS0004;MWAIS0005;MWAIS0006;MWAIS0007;MWAIS0008;MWAIS0009;MWAIS0010;MWAIS0011;MWAIS0012;MWAIS0013;MWAIS0014;MWAIS0015;MWAIS0016;MWAIS0017
+ $(NoWarn);MWAIS0001;MWAIS0002;MWAIS0003;MWAIS0004;MWAIS0005;MWAIS0006;MWAIS0007;MWAIS0008;MWAIS0009;MWAIS0010;MWAIS0011;MWAIS0012;MWAIS0013;MWAIS0014;MWAIS0015;MWAIS0016;MWAIS0017;MWAIS0019