File: ai_model_download_progress_manager.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (241 lines) | stat: -rw-r--r-- 8,845 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ai/ai_model_download_progress_manager.h"

#include "base/functional/bind.h"
#include "base/types/pass_key.h"
#include "chrome/browser/ai/ai_utils.h"
#include "components/update_client/crx_update_item.h"
#include "components/update_client/update_client.h"

namespace on_device_ai {

namespace {

bool IsDownloadEvent(const component_updater::CrxUpdateItem& item) {
  // See class comment: components/update_client/component.h
  switch (item.state) {
    case update_client::ComponentState::kDownloading:
    case update_client::ComponentState::kUpdating:
    case update_client::ComponentState::kUpToDate:
    case update_client::ComponentState::kDownloadingDiff:
    case update_client::ComponentState::kUpdatingDiff:
      return item.downloaded_bytes >= 0 && item.total_bytes >= 0;
    case update_client::ComponentState::kNew:
    case update_client::ComponentState::kChecking:
    case update_client::ComponentState::kCanUpdate:
    case update_client::ComponentState::kUpdated:
    case update_client::ComponentState::kUpdateError:
    case update_client::ComponentState::kRun:
    case update_client::ComponentState::kLastStatus:
      return false;
  }
}

bool IsAlreadyInstalled(const component_updater::CrxUpdateItem& item) {
  // See class comment: components/update_client/component.h
  switch (item.state) {
    case update_client::ComponentState::kUpdated:
    case update_client::ComponentState::kUpToDate:
      return true;
    case update_client::ComponentState::kNew:
    case update_client::ComponentState::kChecking:
    case update_client::ComponentState::kCanUpdate:
    case update_client::ComponentState::kDownloading:
    case update_client::ComponentState::kUpdating:
    case update_client::ComponentState::kUpdateError:
    case update_client::ComponentState::kRun:
    case update_client::ComponentState::kDownloadingDiff:
    case update_client::ComponentState::kUpdatingDiff:
    case update_client::ComponentState::kLastStatus:
      return false;
  }
}

}  // namespace

AIModelDownloadProgressManager::AIModelDownloadProgressManager() = default;
AIModelDownloadProgressManager::~AIModelDownloadProgressManager() = default;

void AIModelDownloadProgressManager::AddObserver(
    component_updater::ComponentUpdateService* component_update_service,
    mojo::PendingRemote<blink::mojom::ModelDownloadProgressObserver>
        observer_remote,
    base::flat_set<std::string> component_ids) {
  reporters_.emplace(std::make_unique<Reporter>(*this, component_update_service,
                                                std::move(observer_remote),
                                                std::move(component_ids)));
}

void AIModelDownloadProgressManager::RemoveReporter(Reporter* reporter) {
  CHECK(reporter);
  reporters_.erase(reporter);
}

int AIModelDownloadProgressManager::GetNumberOfReporters() {
  return reporters_.size();
}

AIModelDownloadProgressManager::Reporter::Reporter(
    AIModelDownloadProgressManager& manager,
    component_updater::ComponentUpdateService* component_update_service,
    mojo::PendingRemote<blink::mojom::ModelDownloadProgressObserver>
        observer_remote,
    base::flat_set<std::string> component_ids)
    : manager_(manager),
      observer_remote_(std::move(observer_remote)),
      component_ids_(std::move(component_ids)) {
  CHECK(component_update_service);

  observer_remote_.set_disconnect_handler(base::BindOnce(
      &AIModelDownloadProgressManager::Reporter::OnRemoteDisconnect,
      weak_ptr_factory_.GetWeakPtr()));

  // Don't watch any components that are already installed.
  for (auto iter = component_ids_.begin(); iter != component_ids_.end();) {
    component_updater::CrxUpdateItem item;
    bool success = component_update_service->GetComponentDetails(*iter, &item);

    // When `success` is false, it means the component hasn't been registered
    // yet. `GetComponentDetails` doesn't fill out `item` in this case, and we
    // can just treat the component as if it had a state of `kNew`.
    if (success && IsAlreadyInstalled(item)) {
      iter = component_ids_.erase(iter);
    } else {
      ++iter;
    }
  }

  // If there are no component ids to observe, just send zero and one hundred
  // percent.
  if (component_ids_.empty()) {
    observer_remote_->OnDownloadProgressUpdate(
        0, AIUtils::kNormalizedDownloadProgressMax);
    observer_remote_->OnDownloadProgressUpdate(
        AIUtils::kNormalizedDownloadProgressMax,
        AIUtils::kNormalizedDownloadProgressMax);
    return;
  }

  // Watch for progress updates.
  component_updater_observation_.Observe(component_update_service);
}

AIModelDownloadProgressManager::Reporter::~Reporter() = default;

void AIModelDownloadProgressManager::Reporter::OnRemoteDisconnect() {
  // Destroy `this` when the `ModelDownloadProgressObserver` is garbage
  // collected in the renderer.
  manager_->RemoveReporter(this);
}

int64_t AIModelDownloadProgressManager::Reporter::GetDownloadedBytes() {
  int64_t bytes_so_far = 0;
  for (const auto& [id, downloaded_bytes] : observed_downloaded_bytes_) {
    bytes_so_far += downloaded_bytes;
  }
  return bytes_so_far;
}

void AIModelDownloadProgressManager::Reporter::ProcessEvent(
    const component_updater::CrxUpdateItem& item) {
  CHECK_GE(item.downloaded_bytes, 0);
  CHECK_GE(item.total_bytes, 0);

  auto iter = observed_downloaded_bytes_.find(item.id);

  // If we've seen this component before, then just update the downloaded bytes
  // for it.
  if (iter != observed_downloaded_bytes_.end()) {
    iter->second = item.downloaded_bytes;
    return;
  }

  // We shouldn't already be ready to report if a component is not in the
  // `component_downloaded_bytes_` map.
  CHECK(!ready_to_report_);

  auto result =
      observed_downloaded_bytes_.insert({item.id, item.downloaded_bytes});
  CHECK(result.second);

  components_total_bytes_ += item.total_bytes;

  // If we have observed the downloaded bytes of all our components then we're
  // ready to start reporting.
  ready_to_report_ = observed_downloaded_bytes_.size() == component_ids_.size();

  if (!ready_to_report_) {
    return;
  }

  last_reported_progress_ = 0;
  last_progress_time_ = base::TimeTicks::Now();

  // We don't want to include already downloaded bytes in our progress
  // calculation, so determine it for later calculations and remove it now
  // from components_total_bytes_.
  already_downloaded_bytes_ = GetDownloadedBytes();
  components_total_bytes_ -= already_downloaded_bytes_;

  // Must always fire the zero progress event first.
  observer_remote_->OnDownloadProgressUpdate(
      0, AIUtils::kNormalizedDownloadProgressMax);
}

void AIModelDownloadProgressManager::Reporter::OnEvent(
    const component_updater::CrxUpdateItem& item) {
  if (!IsDownloadEvent(item) || !component_ids_.contains(item.id)) {
    return;
  }

  ProcessEvent(item);

  // Wait for the total number of bytes to be downloaded to become determined.
  if (!ready_to_report_) {
    return;
  }

  // Calculate the total number of bytes downloaded so far. Don't include bytes
  // that were already downloaded before we determined the total bytes.
  int64_t bytes_so_far = GetDownloadedBytes() - already_downloaded_bytes_;

  CHECK_GE(bytes_so_far, 0);
  CHECK_LE(bytes_so_far, components_total_bytes_);

  // Only report this event if we're at 100% or if more than 50ms has passed
  // since the last time we reported a progress event.
  if (bytes_so_far != components_total_bytes_) {
    base::TimeTicks current_time = base::TimeTicks::Now();
    if (current_time - last_progress_time_ <= base::Milliseconds(50)) {
      return;
    }
    last_progress_time_ = current_time;
  }

  // Determine the normalized progress.
  //
  // If `components_total_bytes_` is zero, we should have downloaded zero bytes
  // out of zero meaning we're at 100%. So set it to
  // `kNormalizedDownloadProgressMax` to avoid dividing by zero in
  // `NormalizeModelDownloadProgress`.
  int normalized_progress = components_total_bytes_ == 0
                                ? AIUtils::kNormalizedDownloadProgressMax
                                : AIUtils::NormalizeModelDownloadProgress(
                                      bytes_so_far, components_total_bytes_);

  // Don't report progress events we've already sent.
  if (normalized_progress <= last_reported_progress_) {
    CHECK(normalized_progress == last_reported_progress_);
    return;
  }
  last_reported_progress_ = normalized_progress;

  // Send the progress event to the observer.
  observer_remote_->OnDownloadProgressUpdate(
      normalized_progress, AIUtils::kNormalizedDownloadProgressMax);
}

}  // namespace on_device_ai