mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-05 00:04:35 +00:00
Moved temporary files into a folder of their own below the data directory (#1245)
This commit is contained in:
1 parent
ddfc632b63
commit
12d3e1ec6c
52 files changed
+1219
-396
No files matched your search
@@ -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.");
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using AIStudio.Settings;
|
||||
|
||||
namespace AIStudio.Tools.Services.Indexing;
|
||||
|
||||
/// <summary>
|
||||
@@ -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.
|
||||
/// </remarks>
|
||||
internal static class MailAttachmentFiles
|
||||
{
|
||||
private const string DIRECTORY_NAME = "mailAttachments";
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="extension">The extension of the attachment, checked against the known document types beforehand, without a dot.</param>
|
||||
/// <returns>The path, where no file exists yet.</returns>
|
||||
/// <exception cref="InvalidOperationException">The data directory is not known yet.</exception>
|
||||
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}");
|
||||
}
|
||||
/// <exception cref="InvalidOperationException">AI Studio has not set its temporary folder yet.</exception>
|
||||
public static string CreatePath(string extension) => TemporaryFiles.GetFilePath($".{extension}");
|
||||
|
||||
/// <summary>
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes every file an earlier session of AI Studio left behind.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Only to be called before any mailbox is synced, since it deletes the files of a running sync as well.
|
||||
/// </remarks>
|
||||
/// <param name="logger">The logger.</param>
|
||||
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);
|
||||
}
|
||||
@@ -498,8 +498,8 @@ public sealed class MediaTranscriptionService(
|
||||
/// <returns>A typed terminal result.</returns>
|
||||
private async Task<MediaTranscriptionResult> 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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -8,70 +8,43 @@ public sealed partial class PluginInstallService
|
||||
/// Creates a staging directory for a plugin that is about to be installed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.<br/><br/>
|
||||
/// 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.<br/><br/>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="prefix">The prefix of the staging directory name, naming the caller.</param>
|
||||
/// <param name="stagingDirectory">The created staging directory.</param>
|
||||
/// <param name="issue">A user-facing issue when the staging directory could not be created.</param>
|
||||
/// <returns>True when the staging directory exists, false otherwise.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes staging directories which an earlier installation left behind, e.g. after a crash.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a directory and falls back to copying it when the move crosses a file system boundary.
|
||||
/// </summary>
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<PluginInstallService> logger;
|
||||
|
||||
@@ -17,13 +17,6 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
|
||||
|
||||
private const string PLUGIN_FILE_NAME = "plugin.lua";
|
||||
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
@@ -37,8 +30,8 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
|
||||
/// The archive contains the plugin root contents, so <c>plugin.lua</c> is located at the archive root.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="plugin">The local plugin to archive and share.</param>
|
||||
/// <param name="pluginRoot">The validated plugin root directory.</param>
|
||||
/// <param name="token">Cancellation token for archive creation.</param>
|
||||
/// <returns>The share result, including the retained temporary archive path when successful.</returns>
|
||||
private async Task<PluginShareResult> 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))
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
using AIStudio.Settings;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
/// <summary>
|
||||
/// One-shot startup service that removes transcript staging left by crashes or forced shutdowns.
|
||||
/// </summary>
|
||||
public sealed class TranscriptStagingCleanupService(ILogger<TranscriptStagingCleanupService> logger) : BackgroundService
|
||||
{
|
||||
/// <summary>Waits for the data directory, performs one cleanup pass, and then exits.</summary>
|
||||
/// <param name="stoppingToken">Host shutdown token.</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user